简体   繁体   English

根据 R 中其他列中的值和条件计算新列

[英]Calculate a new column from values and conditions in the other columns in R

I have a csv table like this loaded in R.我在 R 中有一个像这样的 csv 表。

method方法 SOC SOC SOC2 SOC2
WB世界银行 1.5 1.5
Com Com 2.5 2.5
LOI意向书 3.1 3.1

I want to calculate column "SOC2" with conditions from method column like as follows: If the method in the method column is WB, multiply SOC by 10 and put it in SOC2 column.我想使用方法列中的条件计算列“SOC2”,如下所示:如果方法列中的方法是 WB,则将 SOC 乘以 10 并将其放入 SOC2 列。 If the method in the method column is Com, multiply SOC by 20 and put it in SOC2 column.如果方法栏中的方法是Com,则将SOC乘以20并放入SOC2栏中。 if the method in the method column is LOI, multiply SOC by 30 and out ut ub SOC2 Column.如果method列中的method是LOI,则将SOC乘以30,输出ut ub SOC2列。

How can I do that in R please?请问如何在 R 中做到这一点?

Try this:尝试这个:

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

You can do it like this:你可以这样做:

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.

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