使用列名向量替换 NA

Replace NA using a vector of column names

我有一个数据框,其中的列包含 NA,我用 replace_na 替换了这些列。问题是这些列名将来可能会更改,所以我想将这些列名放在一个向量中,然后在 replace_na 函数中使用该向量。我不想一次性更改整个数据框,只更改指定的列。当我如下所示尝试时,代码运行但不会更改数据框。有人可以建议对代码进行任何修改吗?

library(tidyverse)
col1<-c(9,NA,25,26,NA,51)
col2<-c(9,5,25,26,NA,51)
col3<-c(NA,3,25,26,NA,51)
col4<-c(9,1,NA,26,NA,51)

data<-data.frame(col1,col2,col3,col4, stringsAsFactors = FALSE)

columns<-c(col1,col2)

data<-data%>%
  replace_na(list(columns=0))


columns 值应该是字符串,然后你可以使用 is.na 作为 -

columns<-c("col1","col2")

data[columns][is.na(data[columns])] <- 0
data

#  col1 col2 col3 col4
#1    9    9   NA    9
#2    0    5    3    1
#3   25   25   25   NA
#4   26   26   26   26
#5    0    0   NA   NA
#6   51   51   51   51

或使用tidyverse -

library(dplyr)
library(tidyr)

data <- data %>% mutate(across(all_of(columns), replace_na, 0))

一个dplyr选项:

columns <- c("col1" ,"col2")

dplyr::mutate(data, across(columns, replace_na, 0))

Returns:

  col1 col2 col3 col4
1    9    9   NA    9
2    0    5    3    1
3   25   25   25   NA
4   26   26   26   26
5    0    0   NA   NA
6   51   51   51   51

另一种选择是在 map_at:

中使用 coalesce
  • at map_at 中的参数可以是您要修改的列名称的字符向量
  • 然后我们使用coalesce函数指定替换NAs
library(dplyr)
library(purrr)

data %>%
  map_at(c("col1","col2"), ~ coalesce(.x, 0)) %>%
  bind_cols()

# A tibble: 6 x 4
   col1  col2  col3  col4
  <dbl> <dbl> <dbl> <dbl>
1     9     9    NA     9
2     0     5     3     1
3    25    25    25    NA
4    26    26    26    26
5     0     0    NA    NA
6    51    51    51    51