【问题标题】:Create new variable based on stratified cut-offs using ifelse function in R. Iris dataset example使用 R. Iris 数据集示例中的 ifelse 函数基于分层截止值创建新变量
【发布时间】: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


    【解决方案1】:

    创建一个包含物种信息及其各自截止值的截止数据集。

    library(dplyr)
    cut_off_data <- data.frame(Species = c('virginica', 'versicolor'), 
                               cut_off = c(6.5, 6))
    
    cut_off_data
    #     Species cut_off
    #1  virginica     6.5
    #2 versicolor     6.0
    

    将它与您的数据 (iris_2) 连接起来,并创建一个新列,其中 1 表示上述截断值,否则为 0。

    left_join(iris_2, cut_off_data, by = 'Species') %>%
      mutate(Sepal.Length_above = as.integer(Sepal.Length >=cut_off)) -> result
    
    result
    

    在基础 R 中:

    result <- transform(merge(iris_2, cut_off_data, by = 'Species', all.x = TRUE), 
                        Sepal.Length_above = as.integer(Sepal.Length >=cut_off))
    

    【讨论】:

    • 在那之后你尝试过我的left_join 代码吗? left_join(iris_2, cut_off_data,....
    • 在我的回答中,我创建了一个名为 result 的新数据集,其中包含您需要的所有信息。你能检查一下,看看它是否回答了你的问题?
    • 不,我还创建了一个名为Sepal.Length_above 的新列。请参阅mutate(Sepal.Length_above = as.integer(Sepal.Length &gt;=cut_off)) 行。按原样运行我的代码中的所有行并检查对象result
    猜你喜欢
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    相关资源
    最近更新 更多