【问题标题】:Calculate a new column from values and conditions in the other columns in R根据 R 中其他列中的值和条件计算新列
【发布时间】:2021-02-07 10:29:33
【问题描述】:

我在 R 中加载了一个像这样的 csv 表。

method SOC SOC2
WB 1.5
Com 2.5
LOI 3.1

我想使用方法列中的条件计算列“SOC2”,如下所示: 如果方法栏中的方法为WB,则将SOC乘以10并放入SOC2栏中。 如果method栏的method为Com,则将SOC乘以20,放入SOC2栏。 如果method列的method是LOI,SOC乘以30,输出ut ub SOC2列。

请问我如何在 R 中做到这一点?

【问题讨论】:

  • 请使用Rs dput-函数为我们提供样本数据。如果您的数据加载到名为df 的变量中,请使用dput(df) 的输出扩展您的问题。
  • 您可以利用上一个问题的答案来解决此问题stackoverflow.com/questions/65747420/… 此外,很高兴看到您尝试解决此问题。

标签: r


【解决方案1】:

试试这个:

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

【讨论】:

  • 这是一个非常好的方法。谢谢,莱昂纳多。
  • 不客气!如果我的回答对你有帮助,如果你愿意接受它
【解决方案2】:

你可以这样做:

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

【讨论】:

  • 这个方法很棒。谢谢,乔纳斯。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-16
  • 2020-09-24
  • 2018-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多