根据条件更改列,保留原始内容

时间:2018-10-03 11:34:33

标签: r if-statement conditional-statements tidyverse mutate

我将如何在列上设置条件突变,但保留原始内容。

例如,考虑:

DF=data.frame(A=1:10, B=c("fail1", "fail2", rep(NA,8)))

DF=DF %>% mutate(B = ifelse(A<4,paste(B, "less than 4"),B))

我想要产生以下内容:

DF_want=data.frame(A=1:10, B=c("fail1 less than 4", "fail2 less than 4", "less than 4", rep(NA,7)))

但是因为我直接调用列B,而不是B中的特定行,所以这没有发生。

2 个答案:

答案 0 :(得分:3)

我看到的预期输出和实际输出之间的唯一区别是B的第三项,即NA less than 4而不是less than 4。这是因为paste()的工作方式;考虑以下几点:

paste(NA, "a")
# [1] "NA a"

因此,相反:

DF %>% mutate(B = sub("NA", "", ifelse(A < 4,paste(B, "less than 4"), B)))

    A                 B
1   1 fail1 less than 4
2   2 fail2 less than 4
3   3       less than 4
4   4              <NA>
5   5              <NA>
6   6              <NA>
7   7              <NA>
8   8              <NA>
9   9              <NA>
10 10              <NA>

答案 1 :(得分:2)

另一种可能性:

DF %>%
  mutate(B = ifelse(A < 4 & !is.na(B), paste(B, "less than 4"), 
                    ifelse(A < 4 & is.na(B), paste("less than 4"), B))) 

    A                 B
1   1 fail1 less than 4
2   2 fail2 less than 4
3   3       less than 4
4   4              <NA>
5   5              <NA>
6   6              <NA>
7   7              <NA>
8   8              <NA>
9   9              <NA>
10 10              <NA>