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

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

问题描述

我想在 R 中的 data.frame 中附加一列,其中包含行总和和乘积考虑以下数据框

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

我试过了

 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

另一种选择是使用 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天全站免登陆