简体   繁体   中英

multiply columns in dataframe conditionally in R

I have a dataframe (df) as below:

structure(list(m1 = c(1, 2, 3), m2 = c(2, 3, 4), m3 = c(3, 5, 
5)), class = "data.frame", row.names = c("R1", "R2", "R3"))

I want to get the output as below:

structure(list(m1 = c(0, 3, 3), m2 = c(15, 10, 5), m3 = c(40, 
15, 5)), class = "data.frame", row.names = c("R1", "R2", "R3"
))

Explanation of output (dataframe name is out):

out[1,1] = df[1,1]*df[1,2]*df[1,3] - df[1,2]*df[1,3]
out[1,2] = df[1,2]*df[1,3] - df[1,3]
out[1,3] = df[1,3]

As I am working on huge dataset, is there anyway to use data.table for this operation ?

You can do:

a <- structure(list(m1 = c(1, 2, 3), m2 = c(2, 3, 4), 
               m3 = c(3, 5, 5)), class = "data.frame", row.names = c("R1", "R2", "R3"))

b <- structure(list(m1 = c(0, 3, 3), m2 = c(15, 10, 5), 
               m3 = c(40, 15, 5)), class = "data.frame", row.names = c("R1", "R2", "R3"))

myfun <- function(x) {
  rev(diff(c(0, cumprod(rev(x)) )))
}

apply(a, 1, myfun)
b ### test for the correct result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM