Kevin W
Kevin W

Reputation: 101

For loop help (R)

I would like to have a for loop for this:

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() ???

}

And I would like the output to be a vector that consists on 17 months:

Output = c("January 2018", "February 2018", "March 2018", "April 2018", ... , "May 2019")

Thank you very much for your help.

Upvotes: 0

Views: 55

Answers (3)

IRTFM
IRTFM

Reputation: 263381

There's already a system supplied vector of month names: month.name. Since paste is vectorized and does recycling, there's no need for a for loop and the default separator for paste is " ", so the code could just be:

 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"     

The other way to do it would be with format applied to seq.Date results:

 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"  

See ?seq.Date and ?format.Date

Upvotes: 2

yarnabrina
yarnabrina

Reputation: 1666

Another option will be this:

> 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"

Upvotes: 2

Bruce Schardt
Bruce Schardt

Reputation: 210

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" 

Upvotes: 1

Related Questions