R 将 NA 替换为除 * 之外的所有列

Jas*_*ter 4 select r tidyr tidyselect

library(tidyverse)
df <- tibble(Date = c(rep(as.Date("2020-01-01"), 3), NA),
             col1 = 1:4,
             thisCol = c(NA, 8, NA, 3),
             thatCol = 25:28,
             col999 = rep(99, 4))
#> # A tibble: 4 x 5
#>   Date        col1  thisCol thatCol col999
#>   <date>     <int>    <dbl>   <int>  <dbl>
#> 1 2020-01-01     1       NA      25     99
#> 2 2020-01-01     2        8      26     99
#> 3 2020-01-01     3       NA      27     99
#> 4 NA             4        3      28     99
Run Code Online (Sandbox Code Playgroud)

我实际的 R 数据框有数百列,这些列的命名并不明确,但可以通过df上面的数据框进行近似。

我想用 替换所有值,NA0几列除外(在我的示例中,我想省略列DatethatCol列。我想以这种方式执行此操作:

df %>% replace(is.na(.), 0)
#> Error: Assigned data `values` must be compatible with existing data.
#> i Error occurred for column `Date`.
#> x Can't convert <double> to <date>.
#> Run `rlang::last_error()` to see where the error occurred.
Run Code Online (Sandbox Code Playgroud)

下面显示了我完成“除了”之外的所有内容替换 NA 的不成功的想法。

df %>% replace(is.na(c(., -c(Date, thatCol)), 0))
df %>% replace_na(list([, c(2:3, 5)] = 0))
df %>% replace_na(list(everything(-c(Date, thatCol)) = 0))
Run Code Online (Sandbox Code Playgroud)

有没有办法以我需要的方式选择所有内容?有数百列,命名不一致,因此一一键入它们不是一个实际的选择。

Ron*_*hah 7

您可以使用mutate_at

library(dplyr)
Run Code Online (Sandbox Code Playgroud)

按名称删除它们

df %>% mutate_at(vars(-c(Date, thatCol)), ~replace(., is.na(.), 0))
Run Code Online (Sandbox Code Playgroud)

按位置删除它们

df %>% mutate_at(-c(1,4), ~replace(., is.na(.), 0))
Run Code Online (Sandbox Code Playgroud)

按名称选择它们

df %>% mutate_at(vars(col1, thisCol, col999), ~replace(., is.na(.), 0))
Run Code Online (Sandbox Code Playgroud)

按位置选择它们

df %>% mutate_at(c(2, 3, 5), ~replace(., is.na(.), 0))
Run Code Online (Sandbox Code Playgroud)

如果你想使用replace_na

df %>% mutate_at(vars(-c(Date, thatCol)), tidyr::replace_na, 0)
Run Code Online (Sandbox Code Playgroud)

请注意,mutate_at很快就会被acrossin取代dplyr 1.0.0