36

考虑iris数据:

 iris 
        Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
    1            5.1         3.5          1.4         0.2     setosa
    2            4.9         3.0          1.4         0.2     setosa
    3            4.7         3.2          1.3         0.2     setosa
    4            4.6         3.1          1.5         0.2     setosa
    5            5.0         3.6          1.4         0.2     setosa
    6            5.4         3.9          1.7         0.4     setosa
    7            4.6         3.4          1.4         0.3     setosa

Sepal.Length我想根据变量中的值与固定限制/截止值的比较来创建一个新列,例如检查值是大于还是小于 5:

if Sepal.Length >= 5 assign "UP" else assign "DOWN"到一个新的列“条例”。

这样做的方法是什么?

4

3 回答 3

72

尝试

iris$Regulation <- ifelse(iris$Sepal.Length >=5, "UP", "DOWN")
于 2013-02-22T04:22:31.107 回答
24

为了更新可能的规范,该包dplyr具有mutate允许您以矢量化方式在 data.frame 中创建新列的功能:

library(dplyr)
iris_new <- iris %>%
    mutate(Regulation = if_else(Sepal.Length >= 5, 'UP', 'DOWN'))

这会创建一个名为的新列Regulation,其中包含'UP''DOWN'基于将条件应用于Sepal.Length列。

case_when函数(也来自dplyr)提供了一种将多个条件链接在一起的易于阅读的方式:

iris %>%
    mutate(Regulation = case_when(Sepal.Length >= 5 ~ 'High',
                                  Sepal.Length >= 4.5 ~ 'Mid',
                                  TRUE ~ 'Low'))

这就像if_else除了不是 1 个条件返回值为 TRUE 和 FALSE 之外,每一行都有条件(左侧~)和返回值(右侧~),如果 TRUE 则返回。如果为假,则进入下一个条件。

在这种情况下,行 whereSepal.Length >= 5将 return 'High',行 where Sepal.Length < 5(因为第一个条件必须失败)&Sepal.Length >= 4.5将 return 'Mid',所有其他行将 return 'Low'。由于TRUEis always TRUE,因此它用于提供默认值。

于 2019-03-13T21:58:52.500 回答
6

没有ifelse

iris$Regulation <- c("DOWN", "UP")[ (iris$Sepal.Length >= 5) + 1 ]

基准测试,比ifelse快约 14 倍:

bigX <- runif(10^6, 0, 10)

bench::mark(
  x1 = c("DOWN", "UP")[ (bigX >= 5) + 1 ],
  x2 = ifelse(bigX >=5, "UP", "DOWN"),
  x3 = dplyr::if_else(bigX >= 5, "UP", "DOWN")
)
# # A tibble: 3 x 14
# expression     min    mean  median     max `itr/sec` mem_alloc  n_gc n_itr total_time result memory
# <chr>      <bch:t> <bch:t> <bch:t> <bch:t>     <dbl> <bch:byt> <dbl> <int>   <bch:tm> <list> <list>
# x1          19.1ms  23.9ms  20.5ms  31.6ms     41.9     22.9MB     9    22      525ms <chr ~ <Rpro~
# x2         278.9ms 280.2ms 280.2ms 281.5ms      3.57   118.3MB     4     2      560ms <chr ~ <Rpro~
# x3          47.8ms  64.2ms  54.1ms 138.8ms     15.6     68.7MB    11     8      514ms <chr ~ <Rpro~
于 2019-03-13T22:01:38.890 回答