If I want to avoid a for loop (and use lapply or do.call instead), how can I merge data frames like below (cbind is not really an option in my case). I have a given "base" data frame and a function that creates several data frames to add.
set.seed(1)
# creates example data frames
newCol <- function(x) {
add_df <-data.frame("nr" = 1:5, runif(1))
colnames(add_df)[2] <- x
return(add_df)
}
# for-version - gives wanted result, but with for
df_base <- newCol("A")
for (x in x_vec) {
df_base <- merge(df_base, newCol(x), on = "nr")
}
print(df_base)
# cbind - creates unnecessary "nr"-columns
df_base <- newCol("A")
do.call(cbind, lapply(x_vec, newCol))
# want: solution with merge (!) and lapply/do.call
Thx & kind regards