Adding a new column to each element in a list of tables or data frames

An alternate solution is to use cbind, and taking advantage of the fact that R will recylce values of a shorter vector.

For Example

x <- df2  # from above
cbind(x, NewColumn="Singleton")
 #    x y NewColumn
 #  1 4 d Singleton
 #  2 5 e Singleton
 #  3 6 f Singleton

There is no need for the use of rep. R does that for you.

Therfore, you could put cbind(filelist[[i]], ID[[i]]) in your for loop or as @Sven pointed out, you can use the cleaner mapply:

filelist <- mapply(cbind, filelist, "SampleID"=ID, SIMPLIFY=F)

Leave a Comment