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:

  1. don't use for when can use lapply or more genrally xxapply family.
  2. don't append row of data.frame inside loop. inefficient. should pre-allocate. using lapply you.
  3. don't use $ inside function. should use [ operator
  4. 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

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -