HBat
HBat

Reputation: 5692

Converting the values in all columns to a certain value in tibble/dplyr

I have a tibble object and I want to replace all of the columns except certain ones with a value (say NA or 0). I can able to do it without pipes %>% but how can I do it with %>%?

library(tibble)  
dtf <- tibble(id = c('12', '22', '33', '40'),
              x1 = c(0, 2, 3, 4),
              a2 = c(1, 0, 3, 0),
              c5 = c('a', 'b', 'c', 'd'))

# This raises an error:
dtf %>% select(-id) <- NA

Error in dtf %>% select(-id) <- NA : could not find function "%>%<-"

# This works:
dtf[, colnames(dtf) != 'id'] <- NA
dtf
# A tibble: 4 x 4
  id    x1    a2    c5   
  <chr> <lgl> <lgl> <lgl>
1 12    NA    NA    NA   
2 22    NA    NA    NA   
3 33    NA    NA    NA   
4 40    NA    NA    NA 

I believe I should use mutate() or mutate_all() but I couldn't figure out. One similar SO answer offered na_if() for NA values but I cannot make it work for this case.

Upvotes: 2

Views: 697

Answers (3)

Vishal Katti
Vishal Katti

Reputation: 652

you just do dtf[,colnames(dtf) != "id"] <- NA in one go... this will replace all column values except id with NA

Upvotes: 0

Fnguyen
Fnguyen

Reputation: 1177

Depends what you want to do.

  1. Mutate all variables in the same way and select by name/place:
df %>%
mutate_at(.vars = c("x1","a2","c5"), funs(case_when(is.na(.) ~ 0,TRUE ~ .)))

# or 

df %>%
mutate_at(.vars = -id, funs(case_when(is.na(.) ~ 0,TRUE ~ .)))
  1. Mutate all variables in the same way and select by type:
df %>%
mutate_if(is.numeric, funs(case_when(is.na(.) ~ 0,TRUE ~ .)))

Upvotes: 1

akrun
akrun

Reputation: 887158

If the intention is to update the columns, use mutate_at

library(dplyr)
dtf <- dtf %>% 
           mutate_at(vars(-id), ~ NA)

If we need to replace with 0

dtf <- dtf %>%
          mutate_at(vars(-id), replace_na, 0)

Upvotes: 2

Related Questions