【发布时间】: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