【问题标题】:How to sum multiple columns in two data frames in r如何在r中对两个数据框中的多列求和
【发布时间】:2021-04-30 21:59:44
【问题描述】:

这个问题与这个问题类似:R: Sum column wise value of two/more data frames having same variables (column names) and take Date column as reference,但我的 dfs 有不同的列数、列名并且没有特定的参考列。

修改他的例子:

df1:

      V1  V2  V3  
       2   4   5   
       3   5   7 

df2:

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

我想要的结果是:

df3:

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

我不断收到如下错误:

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.

我尝试过合并、加入、...等

【问题讨论】:

    标签: r join merge


    【解决方案1】:

    这是一个基本的 R 选项:

    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
    

    数据

    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))
    

    【讨论】:

    • 优雅!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-04
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多