簡體   English   中英

在 R 中有條件地乘以數據框中的列

[英]multiply columns in dataframe conditionally in R

我有一個數據框(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"))

我想得到如下輸出:

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"
))

輸出說明(數據幀名稱已出):

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]

當我正在處理龐大的數據集時,是否可以使用 data.table 進行此操作?

你可以做:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM