R中不同数据帧(不同长度)的列总和

Sum of columns from different data frames (different lengths) in R

我是 R 的新手,我必须做一些事情: 我必须得到以下的最终结果:final_x=df1+df2+df3 其中 df1、df2 和 df3 是三个数据框,每个有 1 列(但长度不同),如下所示:

df1

      x1
1.    1
2.    4
3.    4
4.    6

df2

      x2
1.     1
2.     4
3.     4
4.     6
5.     6
6.     6
7.     8

df3

       x3
1.     1
2.     4
3.     4
4.     6
5.     6

作为最终结果,我希望我的 final_x 如下所示:

final_x

      final
1.       3
2.      12
3.      12
4.      18
5.      12
6.      6
7.      8

所以要从列中获取每个元素的总和,尽管它们的长度不同。基本上,当我尝试对它们进行总结时,我收到错误提示“+”只为同样大小的数据帧定义。

这里展示了我们是如何做到的:

#data:
df1 <- tibble(x1 = c(1,4,4,6))
df2 <- tibble(x2 = c(1,4,4,6,6,6,8))
df3 <- tibble(x3 = c(1,4,4,6,6))

# 1. construct a list
df_list <- list(df1, df2, df3)

#install.packages("qpcR")
library(qpcR)

# 2. Use `cbind.na` from gpcR package to fill the lacking length with `NA`, so all columns have the same length:
df_result <- do.call(qpcR:::cbind.na, df_list)

# 3. Use `rowSums` to sum
df_result$final <- rowSums(df_result, na.rm = TRUE)

# 4. save as dataframe
final_x <- data.frame(final = df_result[,4])

# 5. call result:
final_x
  final
1     3
2    12
3    12
4    18
5    12
6     6
7     8

这是另一个基于 old discussion from R-help at r-project.org 的解决方案。

这利用了 Andrej-Nikolai Spiess 的自定义 base-R 函数 cbind.na()rbind.na()

source("http://www.dr-spiess.de/scripts/cbind.na.R")
source("http://www.dr-spiess.de/scripts/rbind.na.R")

rowSums(cbind.na(df1, df2, df3), na.rm = TRUE)
#[1]  3 12 12 18 12  6  8