Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Create objects in loop named depending on i

Tags:

loops

r

I have nearly the same problem as for loop to output different objects in r but I don't get it even considering the solution here (Sorry): I want to create objects (can be matrix, vector or else) depending on calender years.

I create the actual year as number:

now<-Sys.time()
actualyear<-strftime(now, format="%Y")
actualyear<-as.numeric(actualyear)
class(actualyear)

In this case I want to create 7 objects named test2011, test2012, test2013, .... test2017 with the equivilant calender year as content (test2011 <- 2011, test2012 <- 2012, ....)

for(i in 2011:actualyear) {test[[i]]<-i}
like image 488
Chris Avatar asked Dec 04 '22 21:12

Chris


1 Answers

As pointed out in comments, you can assign a value to a name with assign

for(i in 2011:actualyear) {
  assign(paste0("test", i), i)
}
like image 56
Patrik_P Avatar answered Dec 11 '22 17:12

Patrik_P