r根据一个值对所有列求和 [英] r sum all columns based on one value

查看:286
本文介绍了r根据一个值对所有列求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

获得df:

  ID Val1 Val2 Val3 
A 1 1 1
A 1 1 1
A 1 1 1
B 0 0 1

我想参加基于唯一ID值的所有列的总和。像这样:

  ID Val1 Val2 Val3 
A 3 3 3
B 0 0 1

我尝试过:

  df%>%group_by(ID)%>%summarise_all(funs(sum()))

有人对我做错了什么建议吗?我更喜欢dplyr方法(如果可能)。

解决方案

您需要删除 sum 之后的括号,即您的代码应为:

  df%>%group_by(ID)%>%summarise_all(funs(sum))

在这种情况下键入 sum()调用函数,而仅传递函数名称将其发送给 summarise_all 使用。说现在和现在使用此函数与将函数作为参数传递给其他函数之间是有区别的。同样,键入?sum 将带给您该函数的文档,但?sum()无效。 / p>

Got a df:

ID   Val1    Val2    Val3  
A    1        1       1
A    1        1       1
A    1        1       1
B    0        0       1

I want to take the sum of all the columns, based on a unique ID value. Like this:

ID   Val1    Val2    Val3     
A     3       3       3
B     0       0       1

I tried:

df %>% group_by(ID) %>% summarise_all(funs(sum()))

Anyone have an advice about what I' m doing wrong? I prefer a dplyr approach (if possible).

解决方案

You need to remove the parentheses after sum, i.e., your code should read:

df %>% group_by(ID) %>% summarise_all(funs(sum))

Typing sum() in this case calls the function, whereas passing just the name of the function sends it to be used by summarise_all. It's the difference between saying "use this function here and now," versus, "pass the function, as a parameter, to some other function". Similarly, typing, ?sum will bring you the documentation for the function, but ?sum() is invalid.

这篇关于r根据一个值对所有列求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆