Reputation: 51
I have a dataframe where this column has "Yes", "No", and blank (null). I tried to convert blank into a value, but it didn't work (this code used to work well on other scenarios). This "Agree" column is a factor variable. There is no error message in the console, but the blank is still blank.
Agree
Yes
No
No
Yes
Yes
No
No
Yes
df$Agree[is.na(df$Agree)] <- "No Response"
Upvotes: 0
Views: 96
Reputation: 21
Using forcats you could use the function fct_recode()
.
> df <- tibble(Agree = factor(c('yes', 'no', ' ', 'no', 'yes', 'yes')))
> df
# A tibble: 6 x 1
Agree
<fct>
1 "yes"
2 "no"
3 " "
4 "no"
5 "yes"
6 "yes"
> df %>% mutate(Agree = fct_recode(Agree, "No Response" = " "))
# A tibble: 6 x 1
Agree
<fct>
1 yes
2 no
3 No Response
4 no
5 yes
6 yes
See other examples here.
Upvotes: 2
Reputation: 26218
your blank seems empty string column ''
instead of NA. use
df$Agree[df$Agree == ''] <- "No Response"
See
df
#> Agree
#> 1 Yes
#> 2 No
#> 3
#> 4 No
#> 5 Yes
#> 6 Yes
#> 7
#> 8 No
#> 9 No
#> 10 Yes
df$Agree[df$Agree == ''] <- "No Response"
df
#> Agree
#> 1 Yes
#> 2 No
#> 3 No Response
#> 4 No
#> 5 Yes
#> 6 Yes
#> 7 No Response
#> 8 No
#> 9 No
#> 10 Yes
Created on 2021-07-22 by the reprex package (v2.0.0)
Upvotes: 1