使用dplyr总结R中未知数量的列
Summarizing unknown number of column in R using dplyr
我关注 data.frame (df)
ID1 ID2 Col1 Col2 Col3 Grp
A B 1 3 6 G1
C D 3 5 7 G1
E F 4 5 7 G2
G h 5 6 8 G2
我想实现的是:
- 按 Grp 分组,简单
- 然后总结,以便对于每个组,我对列求和并创建包含所有 ID1 和 ID2 的字符串的列
会是这样的:
df %>%
group_by(Grp) %>%
summarize(ID1s=toString(ID1), ID2s=toString(ID2), Col1=sum(Col1), Col2=sum(Col2), Col3=sum(Col3))
一切都很好,虽然我知道列数(Col1、Col2、Col3),但是我希望能够实现它,以便它适用于具有已知且始终命名为相同 ID1 的数据框、ID2、Grp 和任意数量的未知名称的附加数字列。
有没有办法在 dplyr 中做到这一点。
I would like to be able to implement it so that it would work for a data frame with known and always named the same ID1, ID2, Grp, and any number of additional numeric column with unknown names.
您可以先覆盖 ID 列,然后再按它们分组:
DF %>%
group_by(Grp) %>% mutate_each(funs(. %>% unique %>% sort %>% toString), ID1, ID2) %>%
group_by(ID1, ID2, add=TRUE) %>% summarise_each(funs(sum))
# Source: local data frame [2 x 6]
# Groups: Grp, ID1 [?]
#
# Grp ID1 ID2 Col1 Col2 Col3
# (chr) (chr) (chr) (int) (int) (int)
# 1 G1 A, C B, D 4 8 13
# 2 G2 E, G F, h 9 11 15
我想你会想在折叠成一个字符串之前进行统一化和排序,所以我添加了这些步骤。
使用数据 table 您可以尝试以下操作:
setDT(df)
sd_cols=3:(ncol(df)-1)
merge(df[ ,.(toString(ID1), toString(ID2)), by = Grp], df[ , c(-1,-2), with = F][ , lapply(.SD, sum), by = Grp],by = "Grp")
我关注 data.frame (df)
ID1 ID2 Col1 Col2 Col3 Grp
A B 1 3 6 G1
C D 3 5 7 G1
E F 4 5 7 G2
G h 5 6 8 G2
我想实现的是: - 按 Grp 分组,简单 - 然后总结,以便对于每个组,我对列求和并创建包含所有 ID1 和 ID2 的字符串的列
会是这样的:
df %>%
group_by(Grp) %>%
summarize(ID1s=toString(ID1), ID2s=toString(ID2), Col1=sum(Col1), Col2=sum(Col2), Col3=sum(Col3))
一切都很好,虽然我知道列数(Col1、Col2、Col3),但是我希望能够实现它,以便它适用于具有已知且始终命名为相同 ID1 的数据框、ID2、Grp 和任意数量的未知名称的附加数字列。
有没有办法在 dplyr 中做到这一点。
I would like to be able to implement it so that it would work for a data frame with known and always named the same ID1, ID2, Grp, and any number of additional numeric column with unknown names.
您可以先覆盖 ID 列,然后再按它们分组:
DF %>%
group_by(Grp) %>% mutate_each(funs(. %>% unique %>% sort %>% toString), ID1, ID2) %>%
group_by(ID1, ID2, add=TRUE) %>% summarise_each(funs(sum))
# Source: local data frame [2 x 6]
# Groups: Grp, ID1 [?]
#
# Grp ID1 ID2 Col1 Col2 Col3
# (chr) (chr) (chr) (int) (int) (int)
# 1 G1 A, C B, D 4 8 13
# 2 G2 E, G F, h 9 11 15
我想你会想在折叠成一个字符串之前进行统一化和排序,所以我添加了这些步骤。
使用数据 table 您可以尝试以下操作:
setDT(df)
sd_cols=3:(ncol(df)-1)
merge(df[ ,.(toString(ID1), toString(ID2)), by = Grp], df[ , c(-1,-2), with = F][ , lapply(.SD, sum), by = Grp],by = "Grp")