我想要一个for循环:
months = c("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
years = c(2018, 2019)
input = 17
for (i in 1:input) {
output[i] = paste(months[i], years[i], sep = " ")????
NEED HELP HERE. rep() ???
}
我希望输出为包含17个月的向量:
Output = c("January 2018", "February 2018", "March 2018", "April 2018", ... , "May 2019")
非常感谢您的帮助。
答案 0 :(得分:2)
已经有系统提供的月份名称向量:month.name
。由于粘贴是矢量化的并且可以回收,因此不需要for
循环,并且粘贴的默认分隔符为“”,因此代码可以是:
output <- paste( month.name, rep( years, each=12) )[1:17]
# test result ----
> output
[1] "January 2018" "February 2018" "March 2018" "April 2018" "May 2018" "June 2018"
[7] "July 2018" "August 2018" "September 2018" "October 2018" "November 2018" "December 2018"
[13] "January 2019" "February 2019" "March 2019" "April 2019"
另一种方法是将format
应用于seq.Date
结果:
output <- format( seq( as.Date('2018-01-01'), as.Date('2019-04-01'), by="month") ,
"%B %Y" ) # argument to the format parameter for output
#---------------------
> output
[1] "January 2018" "February 2018" "March 2018" "April 2018" "May 2018" "June 2018"
[7] "July 2018" "August 2018" "September 2018" "October 2018" "November 2018" "December 2018"
[13] "January 2019" "February 2019" "March 2019" "April 2019"
请参见?seq.Date
和?format.Date
答案 1 :(得分:2)
另一个选择是:
> c(outer(month.name, 2018:2019, paste))[1:17]
[1] "January 2018" "February 2018" "March 2018"
[4] "April 2018" "May 2018" "June 2018"
[7] "July 2018" "August 2018" "September 2018"
[10] "October 2018" "November 2018" "December 2018"
[13] "January 2019" "February 2019" "March 2019"
[16] "April 2019" "May 2019"
答案 2 :(得分:1)
c(paste(months,"2018"),paste(months,"2019"))[1:17]
## [1] "January 2018" "February 2018" "March 2018" "April 2018" "May 2018" "June 2018"
## [7] "July 2018" "August 2018" "September 2018" "October 2018" "November 2018" "December 2018"
## [13] "January 2019" "February 2019" "March 2019" "April 2019" "May 2019"