ahtmatrix ahtmatrix - 1 month ago 10
R Question

How do I add a new column to a dataframe after each for loop?

I'm trying to save a numeric vector that is calculated in a for loop, and then save that into a new column in a dataframe at the end of the for loop.

d.dataframe = NULL
for (i in 1:length(viral_raw)) {

scores <- PWMscoreStartingAt(human.pwm, viral_raw[[i]], starting.at = 1:99)

d.dataframe$i <-scores
}


But right now its overwriting the i'th column everytime

Answer

As I commented above, you should delete d.dataframe$i line and then add d.dataframe=cbind(d.dataframe,scores)

The final code will look like:

d.dataframe = NULL
for (i in 1:length(viral_raw)) {

  scores <- PWMscoreStartingAt(human.pwm, viral_raw[[i]], starting.at = 1:99)

  d.dataframe=cbind(d.dataframe,scores)
}