I have a pretty simple problem, but I am new to R. I have over 300 dataframes such as these:
DF1 <- data.frame(replicate(5,sample(1:10,5,rep=TRUE)))
DF2 <- data.frame(replicate(5,sample(11:20,8,rep=TRUE)))
DF3 <- data.frame(replicate(5,sample(21:30,3,rep=TRUE)))
I make a list out of them:
list <- lapply(paste0('DF',seq(1,3)), get)
My goal is to combine these data frames and print them side by side. The reason i cannot use functions list merge, cbind is that I dont wish to combine according to any column as reference.
[DF][1]
Now, cbind.fill() from the rowr package does the job when I pass the DFs seperately. But how do I pass the list to it? It does not work when I do cbind.fill(list)
After searching I found merge_recurse(list), but it does not do the job. Thanks in advance
We can use do.call
library(rowr)
res1 <- do.call(cbind.fill, lst)
identical(res1, cbind.fill(DF1, DF2, DF3))
#[1] TRUE
It is better not to name objects with function names, i.e. we could name it as 'lst' instead of 'list'. Also, for multiple objects, we can use mget instead of 'get'
lst <- mget(paste0('DF', 1:3))
This can also be done without any package. We can replicate the rows by the maximum row in the list of datasets and then cbind
do.call(cbind, lapply(lst, function(x) x[rep(1:nrow(x),
length.out= max(sapply(lst, nrow))),]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With