【问题标题】:Nested if functions [duplicate]嵌套if函数[重复]
【发布时间】:2018-02-06 13:12:59
【问题描述】:

我有树列,我想根据以下条件计算一个新变量(“tot.price”)作为这三个变量的乘积:

A) 如果 V1==1 则将值 1 放入新值“tot.price”

B) 如果 V1==2 则乘以 0.25 的权重并在新值“tot.price”中乘以 V2*V3

C) 如果 V1==3 则乘以 0.5 的权重并在新值“tot.price”中乘以 V2*V3

D) 如果 V1==4 则乘以 0.75 的权重并乘以新值“tot.price”中的 V2*V3

E) 如果 V1==5 则将权重乘以 1 并在新值“tot.price”中乘以 V2*V3

我在下面构建了代码,但它警告我“条件的长度 > 1,并且只会使用第一个元素”。 请问有什么帮助吗?

if (data$V1 == "1") {
  tot.price <- 1
} else {
  if (data$V1 == "2") {
    tot.price <- 0.25 * data$V2 * data$V3
  } else {
    if (data$V1 == "3") {
      tot.price <- 0.5 * data$V2 * data$V3
    } else {
      if (data$V1 == "4") {
        tot.price <- 0.75 * data$sub1_likelihood * data$sub1_severeness
      } else {
        if (data$V1 == "5") {
          tot.price <- data$V2 * data$V3
        } else {
        }
      }
    }
  }
}

【问题讨论】:

  • 使用dplyr::case_when 可能会更简单。查看帮助示例library(dplyr); ?case_when
  • 这几乎肯定是重复的,几乎可以肯定你不想使用“if”,而是应该使用“ifelse”或“switch”。
  • 我已经检查过之前的问题。它是不同的,因为它计算了一半的条件而不是其余的。

标签: r if-statement nested


【解决方案1】:

您确定要使用嵌套 if 吗?怎么样:

ref=data.frame(a=seq(1:5),b=as.character(seq(1:5)))
df=data.frame(V1=as.integer(runif(20,1,6)))

df$tot.price=unlist(sapply(df$V1, function(x) ref[(abs(ref$a-x)<0.001),2]))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-14
    • 2019-02-15
    • 2017-01-14
    • 1970-01-01
    • 2015-06-08
    • 2015-05-10
    • 2015-07-20
    相关资源
    最近更新 更多