0

I want to use the pipe function of dplyr package to change values of a column conditionally. I used below approach -

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

In above result, the first value of Col3 is correctly assigned but not rest. Can someone please help me to understand the correct approach?

Bogaso
  • 2,838
  • 3
  • 24
  • 54
  • It's probably a factor. Convert to character and try again. Something like `df %>% mutate(Col3 = ifelse(Col1 == "a", "aa", as.character(Col1)))` – Sotos Dec 18 '19 at 11:03
  • 1
    Not related to the issue at hand, but using a pipe operator isn't relevant to the problem. `mutate(df, Col = ifelse(Col1 == "a", "aa", Col1))` would have the same result – camille Dec 18 '19 at 14:38

1 Answers1

1

Two approaches :

Either use as.character in ifelse

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

Or use stringsAsFactors = FALSE while constructing the dataframe.

df = data.frame("Col1" = letters[1:6], "Col2" = 1:6, stringsAsFactors = FALSE)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213