如何根据R编程中的条件将列添加到数据帧中

nev*_*int 21 r dataframe

例如,我有以下数据框.我想要做的是在该数据框中添加另一列(第7列).条件是if Sepal.Length >=5 assign "UP" else assign "DOWN".我们称之为"监管"栏目.

 > 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
    8            5.0         3.4          1.5         0.2     setosa
    9            4.4         2.9          1.4         0.2     setosa
    10           4.9         3.1          1.5         0.1     setosa
    ...
Run Code Online (Sandbox Code Playgroud)

在R中这样做的方法是什么?

小智 52

尝试

iris$Regulation <- ifelse(iris$Sepal.Length >=5, "UP", "DOWN")
Run Code Online (Sandbox Code Playgroud)

  • 如果要检查 df 中的哪些元素与不同长度的向量中的元素匹配,是否可以使用向量代替“&gt;=5”? (3认同)

div*_*san 7

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

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

这将创建一个新列Regulation,该列由'UP''DOWN'基于将条件应用于该Sepal.Length列组成。

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

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

就像if_else除了用1返回条件为TRUE和FALSE的条件之外,每行都具有条件​​(条件为~)和返回值(条件为右侧~),如果条件为TRUE,则返回该条件。如果为假,则继续进行下一个条件。

在这种情况下,行,其中Sepal.Length >= 5将返回'High',行,其中Sepal.Length < 5(因为第一个条件已经失败)Sepal.Length >= 4.5将返回'Mid',和所有其他行会返回'Low'。由于TRUE始终为TRUE,因此用于提供默认值。


zx8*_*754 5

没有ifelse

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

基准测试,比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~
Run Code Online (Sandbox Code Playgroud)