0

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

r.user.05apr
  • 5,356
  • 3
  • 22
  • 39
  • 1
    Use the `Reduce` route i.e. `Reduce(function(...) merge(..., by = "nr"), lapply(x_vec, newCol))` BTW, in `merge`, the argument is `by`. May be it is a mixing of `data.table` join syntax – akrun Jan 29 '18 at 09:20
  • 1
    Thanks. Found the right link: https://stackoverflow.com/questions/14096814/merging-a-lot-of-data-frames – r.user.05apr Jan 29 '18 at 09:36

0 Answers0