![](/img/trans.png)
[英]Fuzzy matching between columns of different data frames (of different lengths)
[英]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
這是另一個基於r-project.org 上 R-help 的舊討論的解決方案。
這利用了來自 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.