0
set.seed(1)
df<-data.frame(Q1 = sample(c("y", NA), 10, replace = T, prob = c(1/2, 1/2)), 
               Q2 = sample(c("y", NA), 10, replace = T, prob = c(2/3, 1/3)), 
               Q3 = sample(c("y", NA), 10, replace = T, prob = c(1/3, 2/3)))
> df
     Q1   Q2   Q3
1  <NA>    y    y
2  <NA>    y <NA>
3     y <NA> <NA>
4     y    y <NA>
5  <NA> <NA> <NA>
6     y    y <NA>
7     y <NA> <NA>
8     y <NA> <NA>
9     y    y    y
10 <NA> <NA> <NA>

I want to change NA in column Q2 to 0,the expected result as below:

> df
     Q1   Q2   Q3
1  <NA>    y    y
2  <NA>    y <NA>
3     y   0  <NA>
4     y    y <NA>
5  <NA>   0  <NA>
6     y    y <NA>
7     y   0  <NA>
8     y   0  <NA>
9     y    y    y
10 <NA>   0  <NA>

then I tried:

> df %>% .[is.na(.[,'Q2'])]<-0L
Error in df %>% .[is.na(.[, "Q2"])] <- 0L : 
  could not find function "%>%<-"
> df %>% `.[is.na(.[,'Q2'])]`<-0L
Error in df %>% `.[is.na(.[,'Q2'])]` <- 0L : 
  could not find function "%>%<-"
> df %>% `.[is.na(.[,'Q2'])]<-`0L
Error: unexpected numeric constant in "df %>% `.[is.na(.[,'Q2'])]<-`0L"

How to do it?

kittygirl
  • 2,255
  • 5
  • 24
  • 52
  • 4
    What's so bad about `df[is.na(df$Q2), "Q2"] <- 0`. Why do you need to make this much harder to read by using magrittr? – Roland Aug 07 '19 at 06:58
  • @Roland,because I need to use `%>%` after that – kittygirl Aug 07 '19 at 07:04
  • 3
    You don't "need to". You "want to" (which is fine, but there is a difference). – Roland Aug 07 '19 at 07:05
  • 1
    you could use `df %>% replace_na(list(Q2 = 0))` Or `df %>% mutate(Q2 = replace(Q2, is.na(Q2), 0))` – Ronak Shah Aug 07 '19 at 07:05
  • 1
    Unless you definitely need piping after (e.g. because you only want to make the changes once), @Roland raises an excellent point that this is a very good instance where base R is better than tidyverse. – RaphaelS Aug 07 '19 at 07:06

0 Answers0