【发布时间】:2019-09-25 10:37:56
【问题描述】:
考虑以下数据框:
df <- data.frame(numeric=c(1,2,3,4,5,6,7,8,9,10), string=c("a", "a", "b", "b", "c", "d", "d", "e", "d", "f"))
print(df)
numeric string
1 1 a
2 2 a
3 3 b
4 4 b
5 5 c
6 6 d
7 7 d
8 8 e
9 9 d
10 10 f
它有一个数字变量和一个字符串变量。现在,我想创建另一个数据框,其中字符串变量仅显示唯一值列表“a”、“b”、“c”、“d”、“e”、“f”,而数字变量是前一个数据帧中数值之和的结果,得到这个数据帧:
print(new_df)
numeric string
1 3 a
2 7 b
3 5 c
4 22 d
5 8 e
6 10 f
这可以使用 for 循环来完成,但在大型数据集中效率会相当低,我更喜欢其他选项。我尝试过使用dplyr 包,但没有得到预期的结果:
library(dplyr)
> df %>% group_by(string) %>% summarize(result = sum(numeric))
result
1 55
【问题讨论】:
-
试试
dplyr::summarise可能你的summarise被plyr::summarise屏蔽了 -
aggregate(df$numeric, list(df$string), sum) -
您的解决方案是正确的,请尝试@akrun 的建议。否则使用
tally(numeric)而不是summarise(即df %>% group_by(string) %>% tally(numeric))