1

I am trying to merge approx 30 dataframes.

I have saved the global environment as a vector, comma separated, as below;

df_names <- (df1, df2, df3, df4)

Now I am trying to merge all of these dataframes

total <- merge(df_names, by = 'ID')

But I am getting an error;

Error in as.data.frame(y) : argument "y" is missing, with no default
2
  • 1
    Check out ?mget to put them in a list Commented Dec 13, 2017 at 15:57
  • 1
    mget + Reduce should do it. Commented Dec 13, 2017 at 15:58

1 Answer 1

3

Converting comments to an answer, you're probably looking for a combination of mget and Reduce along with merge.

Demo:

df1 <- data.frame(ID = 1:3, var = c("a", "b", "c"))
df2 <- data.frame(ID = c(1, 3, 4), var = c("A", "B", "X"))
df3 <- data.frame(ID = c(2, 3, 4, 5), var = c("X", "Y", "Z", "A")) 
df4 <- data.frame(ID = 1:5, var = letters[1:5])
Reduce(function(x, y) merge(x, y, by = "ID", all = TRUE), mget(paste0("df", 1:4)))
#   ID var.x var.y var.x var.y
# 1  1     a     A  <NA>     a
# 2  2     b  <NA>     X     b
# 3  3     c     B     Y     c
# 4  4  <NA>     X     Z     d
# 5  5  <NA>  <NA>     A     e
# Warning message:
# In merge.data.frame(x, y, by = "ID", all = TRUE) :
#   column names ‘var.x’, ‘var.y’ are duplicated in the result
Sign up to request clarification or add additional context in comments.

3 Comments

I try to run this on my dataframe and it just reproduces the dataframe names: I have currently; df_names <- names(which(unlist(eapply(.GlobalEnv,is.data.frame)))) which gives me the list of df_names. Then I tidy it up by df_names <- paste(as.character(df_names),collapse=", ",sep="") so I have a list of dataframe names such as, df1, df2, df3, df4 etc. and here I would like to call in total <- merge(df_names, by = 'PANID') but I get an error.
@user113156, why would you paste the names together? Why not just leave it as a vector? Try Reduce(function(x, y) merge(x, y, by = "ID", all = TRUE), mget(df_names)) before you do the df_names <- paste(as.character(...), ...).
Yes, thanks it worked! but crashed my computer as the df was too big, but it worked! Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.