r - Iteratively adding new columns to a list of data frames -
i trying write code iterates through list of data frames, adding each new column contains same values older column shifted 1. first value in column na. below code:
for(dataframe in 1:length(listofdataframes)){ newcolumn <- c(na) for(row in 1:(nrow(listofdataframes[[dataframe]]) - 1)){ newcolumn <- append(newcolumn, listofdataframes[[dataframe]]$oldcolumn[row]) } mutate(listofdataframes[[i]], newcolumn = newcolumn) }
however, when execute code in r, error on first dataframe:
replacement has 894 rows, data has 895
what causing error? sorry if easy question, not expert in r.
thank you!
you code concentration of things should avoid in r:
- don't use
for
when can uselapply
or more genrally xxapply family. - don't append row of data.frame inside loop. inefficient. should pre-allocate. using
lapply
you. - don't use
$
inside function. should use[
operator - no need loop on data.frame when can in vectorized manner.
here how :
lapply(listofdataframes, function(dx){ ## assume dx has , "oldcolum" variable transform(dx,newcolumn =c(na,head(oldcolumn,-1)) })
Comments
Post a Comment