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

gcc - MinGW's ld cannot perform PE operations on non PE output file -

timeout - Handshake_timeout on RabbitMQ using python and pika from remote vm -

c# - Search and Add Comment with OpenXML for Word -