0

By assigning date_[c], I have 35 "date_c"'s(below code).

for (c in 1:nrow(datetable2)) {
   assign(paste("date_",c,sep=""),dt2[which(dt2$Date==datetable2$Date[c]),])
  
 }

Now, I want to change each "date_c"'s rownames to 1:length(date_c). I used the code below but it doesn't work. The program says it can not find "date_[d]". How should I change the "date_[d]" issue in the below loophole?

for (d in 1:nrow(datetable2)){
  rownames(date_[d]) <-  seq(length=nrow(date_[d]))
}
YJP
  • 43
  • 6
  • You should avoid `assign()`. It would be easier if you just stored all your data.frames in a list. Then you could apply any function you like to that list. See: https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames – MrFlick Sep 14 '20 at 04:49
  • Got it Thanx. @MrFlick – YJP Sep 14 '20 at 07:58

1 Answers1

0

Get all the date_c daatframes in a list, use lapply to iterate over it and remove the rownames. When we remove the rownames it actually recreates the rownames from 1:nrow(data).

result <- lapply(mget(ls(pattern = 'date_')), function(x) 
                 {rownames(x) <- NULL;x})

result would have a list of dataframes with the rownames as we want. It is better to keep data in a list as it is easier to manage them. If you still want the changes to reflect in the original dataframe you can use list2env.

list2env(result, .GlobalEnv)
Ronak Shah
  • 286,338
  • 16
  • 97
  • 143