[英]multiply columns in dataframe conditionally in R
I have a dataframe (df) as below:我有一个数据框(df)如下:
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 ?当我正在处理庞大的数据集时,是否可以使用 data.table 进行此操作?
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.