Home > database >  How to mutate multiple variables of a tibble to the same value in R at nce
How to mutate multiple variables of a tibble to the same value in R at nce

Time:10-31

I want to mutate the values of columns 2 to 4 t NA. I tried to use mutate across without success.

library(tidyverse)

df <- tibble(year = 2020, a = 1, b = 2, c = 3)


df %>% mutate(across(c(2:4), is.na))
#> # A tibble: 1 x 4
#>    year a     b     c    
#>   <dbl> <lgl> <lgl> <lgl>
#> 1  2020 FALSE FALSE FALSE

# But this gives an error because NA is not a function
# df %>% mutate(across(c(2:4), NA))
Created on 2021-10-30 by the reprex package (v2.0.1)

CodePudding user response:

Use an anonymous function or ~.

library(dplyr)

df %>% mutate(across(c(2:4), ~NA))

#   year a     b     c    
#  <dbl> <lgl> <lgl> <lgl>
#1  2020 NA    NA    NA   

In base R, you can do -

df[2:4] <- NA

CodePudding user response:

If we need the class to be the same as the input for each of the columns, multiply (*) with NA or else NA by default is NA_logical_ which may have clash later when we try to change values in those columns

library(dplyr)
df %>%
    mutate(across(2:4, `*`, NA))
# A tibble: 1 × 4
   year     a     b     c
  <dbl> <dbl> <dbl> <dbl>
1  2020    NA    NA    NA
  • Related