-2

I have list of year_month dataframes. They are like this List = c( A2017_1, A2017_2,....A2017_12, A2018_1, ... A2018_12, ..... ) and so on.

I want to rearrange this list with the months, like this:

 month_1 = c(A2017_1, A2018_1, A2019_1, ....)
 month_2 = c(A2017_2, A2018_2, A2019_2, ....)
.
.

... and so on.

This is what I tried.

for (x in 1:12){
LF <- emp_yymm[grep(str_c('+_', x,'$'), names(emp_yymm))]
LFF <-append(LFF, as.list(LF))
names(LFF)[x]<- str_c('mon_',x)
}

And it failed.

halfer
  • 19,824
  • 17
  • 99
  • 186
서영빈
  • 106
  • 6
  • 2
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Make sure your example uses valid R code. – MrFlick Jan 16 '20 at 16:34

2 Answers2

1

You should really start with some reproducible example, but below is the solution I'm giving assuming some things about your data.

 name <- paste0("A",rep(c("2017","2018","2019","2020"), each = 12), "_",rep(1:12, 4))
 L <- vector("list",48)
 names(L) <- name

 Final <- vector("list",0)
 for(x in 1:12){
   indx <- grep(pattern = paste0("_",x,"$"), x = names(L)) #find index of things ending in _num
   ord <- order(names(L)[indx]) #correct order
   tmp <- L[indx[ord]] # make list subset
   Final <- c(Final,tmp) # build list
 }

I'm assuming that the element names of the list are the Year_month values and you are just trying to reorder the list. If you are trying to make 12 more lists per month you can dynamically name variables with the assign function...

Building a list as I have isn't always best. It is usually better to specify the final length first.

Justin Landis
  • 1,981
  • 7
  • 9
0
for (x in 1:12){
  LF <- emp_yymm[grep(str_c('+_', x,'$'), names(emp_yymm))]
  if(x<10){
  assign(str_c('mon_0',x),LF)
  }
  else{
    assign(str_c('mon_',x),LF)
  }

}

monlist<-mget(ls(pattern="mon_\\d+"))
서영빈
  • 106
  • 6
  • 1
    Generally code only answers aren't particularly useful. You should explain how this code solves the problem. – dwjohnston Jan 17 '20 at 03:13