R总和 [英] Aggregate R sum

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

问题描述

我正在R中编写第一个
程序,作为一个新手,我遇到了一些麻烦,希望您能为我提供帮助。

I'm writting my first program in R and as a newbie I'm having some troubles, hope you can help me.



I've got a data frame like this:

> v1<-c(1,1,2,3,3,3,4)
> v2<-c(13,5,15,1,2,7,4)
> v3<-c(0,3,6,13,8,23,5)
> v4<-c(26,25,11,2,8,1,0)
> datos<-data.frame(v1,v2,v3,v4)
> names(datos)<-c("Position","a1","a2","a3")

> datos
  posicion a1 a2 a3
1        1 13  0 26
2        1  5  3 25
3        2 15  6 11
4        3  1 13  2
5        3  2  8  8
6        3  7 23  1
7        4  4  5  0

我需要对 a1 a2 a3 (在我的实际情况下是从 a1 a51 )按 Position 。我正在尝试使用函数 aggregate(),但它仅适用于均值,而不是总和,我也不知道为什么。

What I need is to sum the data in a1, a2 and a3 (in my real case from a1 to a51) grouped by Position. I'm trying with the function aggregate() but it only works for means, not for sums and I don't know why.

预先感谢

推荐答案

对于 plyr 库。

library("plyr")
ddply(datos, .(Position), colwise(sum))

如果还有其他不应取平均值的非数字列,则可以使用

If you have additional non-numeric columns that shouldn't be averaged, you can use

ddply(datos, .(Position), numcolwise(sum))

这篇关于R总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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