Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
927 views
in Technique[技术] by (71.8m points)

r - Merging dataframes by a vector of dataframe names

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...