[英]R: New column creation using lag values from other columns & many other conditions with data.table
[英]Calculate a new column from values and conditions in the other columns in R
我在 R 中有一個像這樣的 csv 表。
方法 | SOC | SOC2 |
---|---|---|
世界銀行 | 1.5 | |
Com | 2.5 | |
意向書 | 3.1 |
我想使用方法列中的條件計算列“SOC2”,如下所示:如果方法列中的方法是 WB,則將 SOC 乘以 10 並將其放入 SOC2 列。 如果方法欄中的方法是Com,則將SOC乘以20並放入SOC2欄中。 如果method列中的method是LOI,則將SOC乘以30,輸出ut ub SOC2列。
請問如何在 R 中做到這一點?
嘗試這個:
library(dplyr)
df <- data.frame(method = c("WB", "Com", "LOI"), SOC = c(1.5, 2.5, 3.1))
df %>% mutate(SOC2 = case_when(
method == "WB" ~ SOC * 10,
method == "Com" ~ SOC * 20,
method == "LOI" ~ SOC * 30
))
method SOC SOC2
1 WB 1.5 15
2 Com 2.5 50
3 LOI 3.1 93
你可以這樣做:
wbIndices <- df$method == "WB"
ComIndices <- df$method == "Com"
LOIIndices <- df$method == "LOI"
df$SOC2 <- df$SOC[wbIndices]*10
df$SOC2 <- df$SOC[ComIndices]*20
df$SOC2 <- df$SOC[LOIIndices]*30
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.