【发布时间】:2020-05-01 14:02:37
【问题描述】:
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
我的实际 R 数据框有数百列名称不整齐,但可以用上面的 df 数据框近似。
我想用0 替换NA 的所有值,除了几列(在我的示例中,我想省略Date 列和thatCol 列。我想以这种方式进行:
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.
我完成“除此之外的所有”替换 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))
有没有办法以我需要的方式选择所有内容?有数百列,名称不一致,因此逐一键入它们是不切实际的选择。
【问题讨论】:
标签: r select tidyr tidyselect