1

I have a data frame lets say

a   b
1   10
2   13

and I have another data frame where I have 1 value "c" which is equal to 0.3 I want to create column "d" in the first data frame using the following formula

1st row will be 1*10*.3
2nd row will be 2*13*.3

please notice .3 is common.

please suggest an R function for this.

De Novo
  • 7,120
  • 1
  • 23
  • 39

3 Answers3

1

If you want to apply a function to a data frame or matrix by rows, you use apply, with the MARGIN argument as 1. Here the function you want is prod, or since you only have two columns, you could use *. The apply call takes the products row-wise, giving you a vector of length == nrow(df). You multiply that vector directly by 0.3, giving you the values, and assign it to a new column with df$c<-

df$c <- apply(df, 1, prod)*0.3
df
   a  b    c
1  1  2  0.6
2 10 13 39.0

Data:

df <- data.frame(a = c(1, 10), b = c(2, 13))
df
   a  b
1  1  2
2 10 13
De Novo
  • 7,120
  • 1
  • 23
  • 39
1

Using dplyr and assuming that df2 will only contain 1 column named c with 1 row with value = 0.3:

require(dplyr)

df1 <- data.frame(a = c(1, 2), b = c(10, 13))
df2 <- data.frame(c = 0.3)

df1 %>%
  mutate(d = a * b * df2$c)
Anonymous
  • 131
  • 1
  • 4
0

Another option is Reduce with *

df$c <- Reduce(`*`, df) * 0.3
df$c
#[1]  0.6 39.0

Or we can use rowProds from matrixStats

library(matrixStats)
df$c <- 0.3 * rowProds(as.matrix(df))
akrun
  • 874,273
  • 37
  • 540
  • 662