如何使用dplyr或其他软件包合并两个数据帧? [英] How to combine two data frames using dplyr or other packages?
问题描述
我有两个数据框:
df1 = data.frame(index=c(0,3,4),n1=c(1,2,3))
df1
# index n1
# 1 0 1
# 2 3 2
# 3 4 3
df2 = data.frame(index=c(1,2,3),n2=c(4,5,6))
df2
# index n2
# 1 1 4
# 2 2 5
# 3 3 6
我想将这些加入:
index n
1 0 1
2 1 4
3 2 5
4 3 8 (index 3 in two df, so add 2 and 6 in each df)
5 4 3
6 5 0 (index 5 not exists in either df, so set 0)
7 6 0 (index 6 not exists in either df, so set 0)
给定的数据帧只是大型数据集的一部分.我可以在R中使用 dplyr
或其他软件包吗?
The given data frames are just part of large dataset. Can I do it using dplyr
or other packages in R?
推荐答案
使用 data.table
(对于更大的数据集将非常有效).我没有更改列名称,因为 rbindlist
使用第一个数据集的名称,即.在这种情况下,第二列为 n
(不知道它是功能还是错误).通过 rbindlist
加入数据集后,请按 index
列将其分组,即( by = index
)并进行 n
列( list(n = sum(n))
)
Using data.table
(would be efficient for bigger datasets). I am not changing the column names, as the rbindlist
uses the name of the first dataset ie. in this case n
from the second column (Don't know if it is a feature or bug). Once you join the datasets by rbindlist
, group it by column index
i.e. (by=index
) and do the sum of n
column (list(n=sum(n))
)
library(data.table)
rbindlist(list(data.frame(index=0:6,n=0), df1,df2))[,list(n=sum(n)), by=index]
index n
#1: 0 1
#2: 1 4
#3: 2 5
#4: 3 8
#5: 4 3
#6: 5 0
#7: 6 0
或使用 dplyr
.在此,所有数据集的列名
应该相同.因此,我要在使用 rbind_list
进行 binding
数据集之前进行更改.如果 names
不同,则每个 name
都会有多列.加入数据集后,将其按 index
分组,然后使用 summarize
并执行列 n
的 sum
.
Or using dplyr
. Here, the column names
of all the datasets should be the same. So, I am changing it before binding
the datasets using rbind_list
. If the names
are different, there will be multiple columns for each name
. After joining the datasets, group it by index
and then use summarize
and do the sum
of column n
.
library(dplyr)
nm1 <- c("index", "n")
colnames(df1) <- colnames(df2) <- nm1
rbind_list(df1,df2, data.frame(index=0:6, n=0)) %>%
group_by(index) %>%
summarise(n=sum(n))
这篇关于如何使用dplyr或其他软件包合并两个数据帧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!