我想更换使用的一些变化在数字列的NA mutate_if和replace_na如果可能的话,但不能找出语法.
df <-tibble(
first = c("a", NA, "b"),
second = c(NA, 2, NA),
third = c(10, NA, NA)
)
#> # A tibble: 3 x 3
#> first second third
#> <chr> <dbl> <dbl>
#> 1 a NA 10.0
#> 2 <NA> 2.00 NA
#> 3 b NA NA
Run Code Online (Sandbox Code Playgroud)
最终结果应该是:
#> # A tibble: 3 x 3
#> first second third
#> <chr> <dbl> <dbl>
#> 1 a 0 10.0
#> 2 <NA> 2.00 0
#> 3 b 0 0
Run Code Online (Sandbox Code Playgroud)
我的尝试看起来像:
df %>% mutate_if(is.numeric , replace_na(., 0) )
#>Error: is_list(replace) is not TRUE
Run Code Online (Sandbox Code Playgroud)
Lyn*_*akr 17
df %>% mutate_if(is.numeric , replace_na, replace = 0)
# A tibble: 3 x 3
# first second third
# <chr> <dbl> <dbl>
#1 a 0 10.0
#2 NA 2.00 0
#3 b 0 0
Run Code Online (Sandbox Code Playgroud)
另一个答案中提到的解决方案基于mutate_if中的暂停函数dplyr。建议的替代方案是使用该across()函数。这是使用该解决方案的解决方案:
df %>% \n mutate(\n across(where(is.numeric), ~replace_na(.x, 0))\n )\n\n# A tibble: 3 \xc3\x97 3\n first second third\n <chr> <dbl> <dbl>\n1 a 0 10\n2 NA 2 0\n3 b 0 0\nRun Code Online (Sandbox Code Playgroud)\n