if else函数问题关于返回基于原始数据帧的结果

时间:2017-09-28 02:58:19

标签: r

如果我有以下数据框

df <- data.frame(name = c("sam", "ken", "mary", "kate"),
                 state = c("dead", "dead", "alive", "dead"))

我想创建一个名为success的新二进制变量,如果人们死亡则等于1,如果人们存活则等于0。像这样:

df <- data.frame(name = c("sam", "ken", "mary", "kate"),
                 state = c("dead", "dead", "alive", "dead"),
                 result = c(0, 0, 1, 0))

如何使用ifelse函数在R中编写推荐?非常感谢!

1 个答案:

答案 0 :(得分:1)

要了解有关R中数据转换的更多信息,我建议https://www.tidyverse.org/learn/

具体为http://r4ds.had.co.nz/transform.html


df <- data.frame(name = letters[1:4], state = c("dead", "dead", "alive", "dead"))

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

df %>%
  mutate(result = if_else(state == "alive", 1, 0))
#>   name state result
#> 1    a  dead      0
#> 2    b  dead      0
#> 3    c alive      1
#> 4    d  dead      0