Search code examples
racross

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


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)

Solution

  • 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