Reputation: 99
I recently want to continually multiply many columns and form a new variable in R.
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,]) }
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.
Upvotes: 3
Views: 76
Reputation: 6685
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
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
Upvotes: 3
Reputation: 887028
A convenient function would be rowProds
from matrixStats
, but that would require a matrix
library(matrixStats)
rowProds(as.matrix(t1))
#[1] 2 1 4 4 2 4 1 2 4 1
If we need a base R
option, which works on data.frame
, then use
Reduce(`*`, t1)
#[1] 2 1 4 4 2 4 1 2 4 1
set.seed(24)
t1 <- data.frame(x1=round(round(runif(10),1)+1),x2=round(round(runif(10),1)+1))
Upvotes: 4