【发布时间】:2021-02-16 08:37:28
【问题描述】:
我正在尝试创建一个新变量,例如 iris$Sepal.Length_above,它具有变量的数值和物种相关分类,例如,萼片长度高于 (1) 或低于 (0) 截止值。我将使用 iris 进行说明。
data("iris")
iris_rm <- subset(iris, Species == 'setosa')
iris_2 <- iris[!(iris$Species %in% iris_rm$Species),] #two species
对于没有特定物种截止值的变量,我使用了下面的行
iris_2$Sepal.Width_above <- ifelse(iris_2$Sepal.Width >= 3.0, 1, 0)#1 is above cut-off
现在我也想做同样的事情,但要使用依赖于物种的截止值。假设:
#Species "virginica" has Sepal.Length cut-off: 6.5
#Species "versicolor" has Sepal.Length cut-off: 6.0
我想出的最好的是下面的,但是有两个问题。
library(dplyr)
iris_2$Sepal.Length_above <- if (iris_2$Species == 'virginica'){
ifelse(iris_2$Sepal.Length >= 6.5, 1, 0)
} else (iris_2$Species =='versicolor'){
ifelse(iris_2$Sepal.Length >= 6.0, 1, 0)
View(iris_2)
#problem 1: 6.0 seems to override the 6.5 for virginica
#problem 2: >= and <= seems to be switched
我会非常感激帮助!
【问题讨论】:
标签: r if-statement