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
989 views
in Technique[技术] by (71.8m points)

join - How to sum multiple columns in two data frames in r

This question is similar to this one: R: Sum column wise value of two/more data frames having same variables (column names) and take Date column as reference , but my dfs have different number of columns, columns names and there is not a specific reference column.

Modifying his example:

df1:

      V1  V2  V3  
       2   4   5   
       3   5   7 

df2:

      V1  V5  V2  V4   
       2   4  4   5   
       3   0  5   7

I want the result as:

df3:

      V1  V2  V3  V4  V5
       4   8   5   5   4
       6  10   7   7   0

I keep getting errors like:

Error: Problem with `mutate()` input `..1`.
? Input `..1` can't be recycled to size 28. # 28 because this is referring to my df
? Input `..1` is `colnames(col_name)`.
? Input `..1` must be size 28 or 1, not 5992.
Run `rlang::last_error()` to see where the error occurred.

I've tried with merge, join, by ...etc

question from:https://stackoverflow.com/questions/65912858/how-to-sum-multiple-columns-in-two-data-frames-in-r

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

1 Reply

0 votes
by (71.8m points)

Here's a base R option :

tmp <- cbind(df1, df2)
data.frame(sapply(split.default(tmp, names(tmp)), rowSums))

#  V1 V2 V3 V4 V5
#1  4  8  5  5  4
#2  6 10  7  7  0

data

df1 < -structure(list(V1 = 2:3, V2 = 4:5, V3 = c(5L, 7L)), 
class = "data.frame", row.names = c(NA, -2L))

df2 <- structure(list(V1 = 2:3, V5 = c(4L, 0L), V2 = 4:5, V4 = c(5L, 
7L)), class = "data.frame", row.names = c(NA, -2L))

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

...