使用布尔值创建新列

  • 本文关键字:新列 创建 布尔值 r
  • 更新时间 :
  • 英文 :


使用鸢尾花数据集。假设我想创建一个名为"漂亮的花朵"的新列,满足以下条件:

[(Sepal.Length > 5.0) && (Petal.Length < 1.5)]

我该怎么做?

base R 中:

iris$nice_flower<-(iris$Petal.Length<1.5) & (iris$Sepal.Length>5)
iris[iris$nice_flower==T,] #for verification

一种方法是使用ifelse

iris$nice_flower <- ifelse(iris$Sepal.Length > 5.0 & iris$Petal.Length < 1.5, 1, 0)

另一种选择是使用as.integer(我认为akrun已经提到了这一点),这比使用ifelse更好

as.integer(iris$Sepal.Length > 5.0 & iris$Petal.Length < 1.5)

在函数内使用创建新列

iris <- within(iris , nice_flower <-ifelse(iris$Sepal.Length > 5.0 & iris$Petal.Length < 1.5, T, F))
iris <- subset(iris, nice_flower %in% T)
   > iris$nice_flower <- iris$Sepal.Length > 5.0 & iris$Petal.Length < 1.5
   > result <- iris[iris$nice_flower == T,]
   > result
   #    Sepal.Length Sepal.Width Petal.Length Petal.Width Species nice_flower
   # 1           5.1         3.5          1.4         0.2  setosa        TRUE
   # 15          5.8         4.0          1.2         0.2  setosa        TRUE
   # 17          5.4         3.9          1.3         0.4  setosa        TRUE
   # 18          5.1         3.5          1.4         0.3  setosa        TRUE
   # 29          5.2         3.4          1.4         0.2  setosa        TRUE
   # 34          5.5         4.2          1.4         0.2  setosa        TRUE
   # 37          5.5         3.5          1.3         0.2  setosa        TRUE

最新更新