使用pipe()函数有条件地更改列的值

时间:2019-12-18 11:02:03

标签: r dplyr

我想使用pipe function包中的dplyr来有条件地更改列的值。我用下面的方法-

library(dplyr)
> df = data.frame("Col1" = letters[1:6], "Col2" = 1:6)
> df %>% mutate(Col3 = ifelse(Col1 == "a", "aa", Col1))
  Col1 Col2 Col3
1    a    1   aa
2    b    2    2
3    c    3    3
4    d    4    4
5    e    5    5
6    f    6    6

在以上结果中,Col3的第一个值已正确分配,但没有休息。有人可以帮我了解正确的方法吗?

1 个答案:

答案 0 :(得分:0)

两种方法:

as.character中使用ifelse

library(dplyr)
df %>% mutate(Col3 = ifelse(Col1 == "a", "aa", as.character(Col1)))

或在构造数据框时使用stringsAsFactors = FALSE

df = data.frame("Col1" = letters[1:6], "Col2" = 1:6, stringsAsFactors = FALSE)