R: many nested loops to remove rows in multiple data frames -
i have 18 data frames called regular55, regular56, regular57, collar55, collar56, etc. in each data frame, want delete first row of each nest.
each data frame looks this:
nest interval 1 17 -8005 2 17 183 3 17 186 4 17 221 5 17 141 6 17 30 7 17 158 8 17 23 9 17 199 10 17 51 11 17 169 12 17 176 13 31 905 14 31 478 15 31 40 16 31 488 17 31 16 18 31 203 19 31 54 20 31 341 21 31 54 22 50 -14164 23 50 98 24 50 1438 25 71 240 26 71 725 27 71 819 28 85 -13935 29 85 45 30 85 589 31 85 47 32 85 161 33 85 67
the solution came avoid writing out function each 1 of 18 data frames includes many nested loops:
for (i in 5:7){ (j in 5:7) { (k in c("regular","collar")){ (l in c(unique(paste0(k,i,j,"$nest")))){ paste0(k,i,j)=paste0(k,i,j)[(-c(which((paste0(k,i,j,"$nest")) == l ) [1])),] }}}}
i'm selecting first value @ "which" there "unique" value of nest. however, get:
error in paste0(k, i, j)[(-c(which((paste0(k, i, j, "$nest")) == l)[1])), : incorrect number of dimensions
it might because "paste0(k,i,j)" considered character , not recognized name data frame.
any ideas on how fix this? or other ways delete first rows each nest in every data frame?
thanks comments, problem solved.
originally, divided data frame using loop , grouped 1 list:
for (i in 5:7) { (j in 5:7) { (k in c("regular","collar")){ assign(paste0(k,i,j), df[df$x == & df$y == j & df$z == k,]) }}} df.list=mget(ls(pattern=("[regular,collar][5-7][5-7]")))
i later found way split data frame directly list based on multiple columns (r subsetting data frame multiple data frames based on multiple column values):
df.list= split(df, with(df, interaction(df$x, df$y, df$z)), drop = true)
finally, able apply function remove first rows of each nest:
df.list.updated = lapply(df.list, function(d) d %>% group_by(nest) %>% slice(2:n()))
it easier work list of data frames.
Comments
Post a Comment