如何在nce处将tibble的多个变量突变为R中的相同值

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

我想改变第 2 列到第 4 列的值 NA。我尝试使用 mutate across 但没有成功。

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)

使用匿名函数或~

library(dplyr)

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

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

在基础 R 中,你可以做 -

df[2:4] <- NA

如果我们需要 class 与每一列的输入相同,请将 (*) 乘以 NA 否则默认为 NANA_logical_,稍后当我们尝试更改这些列中的值时可能会发生冲突

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