在data.frame中计算行总和和乘积 [英] calculate row sum and product in data.frame

查看:122
本文介绍了在data.frame中计算行总和和乘积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在R中添加一个列,其中包含行总和和产品
考虑以下数据框架

I would like to append a columns to my data.frame in R that contain row sums and products Consider following data frame

x    y     z
1    2     3
2    3     4
5    1     2

我想获得以下

x    y     z    sum    prod
1    2     3    6       6  
2    3     4    9       24 
5    1     2    8       10

p>

I have tried

 sum = apply(ages,1,add)

但它给了我一个行向量。有一个请给我一个有效的命令来总结和产品,并将它们附加到如上所示的原始数据框架中。

but it gives me a row vector. Can some one please show me an efficient command to sum and product and append them to original data frame as shown above?

推荐答案

尝试

 transform(df, sum=rowSums(df), prod=x*y*z)
 #  x y z sum prod
 #1 1 2 3   6    6
 #2 2 3 4   9   24
 #3 5 1 2   8   10

 transform(df, sum=rowSums(df), prod=Reduce(`*`, df))
 #   x y z sum prod
 #1 1 2 3   6    6
 #2 2 3 4   9   24
 #3 5 1 2   8   10

另一个选择是使用 rowProds matrixStats

 library(matrixStats)
 transform(df, sum=rowSums(df), prod=rowProds(as.matrix(df)))

如果你正在使用 apply

 df[,c('sum', 'prod')] <-  t(apply(df, 1, FUN=function(x) c(sum(x), prod(x))))
 df
 #  x y z sum prod
 #1 1 2 3   6    6
 #2 2 3 4   9   24
 #3 5 1 2   8   10

这篇关于在data.frame中计算行总和和乘积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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