不断地将许多列相乘以形成一个新变量 [英] continually multiply many columns to form a new variable

查看:55
本文介绍了不断地将许多列相乘以形成一个新变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近想连续乘许多列并在R中形成一个新变量.

I recently want to continually multiply many columns and form a new variable in R.

我发现R中有一个 prod 函数,它可以提供许多向量或矩阵中所有元素的乘积.

I found that there is a prod function in R, which could provide the product of all elements in many vectors or matrices.

但是,我不想获得所有元素的乘积.相反,我想获取每一行的乘积.

However, I do not want to get the product of all element. Instead, I want to get the product of each row.

我可以使用带有循环的代码执行以下操作:

I can do it with code with loop as following:

t <-
 data.frame(x1=round(round(runif(10),1)+1),
            x2=round(round(runif(10),1)+1))
for(i in 1:nrow(t)) {    t$y[i] <- prod(t[i,]) }

但是,我想知道是否有更有效的方法或简单的功能,因为我可以像 prod(t $ 1:t $ 2)这样使用并获得所需的结果.

However, I wonder whether there is more efficient way or easy function, in that I can used like prod(t$1:t$2) and get the result I want.

推荐答案

@akrun答案的 base 变体为

The base variant of @akrun's answer would be

x <- matrix(1:20, ncol = 4)

     [,1] [,2] [,3] [,4]
[1,]    1    6   11   16
[2,]    2    7   12   17
[3,]    3    8   13   18
[4,]    4    9   14   19
[5,]    5   10   15   20

apply(x, 1, prod)
[1]  1056  2856  5616  9576 15000

matrixStats :: rowProd()相比,它也可以在 data.frame 上使用.

In contrast to matrixStats::rowProd(), this also works on a data.frame.

x <- as.data.frame(matrix(1:20, ncol = 4))
x$new <- apply(x, 1, prod)

> x
  V1 V2 V3 V4   new
1  1  6 11 16  1056
2  2  7 12 17  2856
3  3  8 13 18  5616
4  4  9 14 19  9576
5  5 10 15 20 15000

这篇关于不断地将许多列相乘以形成一个新变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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