library(tidyverse)
df <- tibble(col1 = c("a", "a", "b", "b", "c", "c"),
col2 = c(2, NA, 5, NA, 7, NA))
#> # A tibble: 6 x 2
#> col1 col2
#> <chr> <dbl>
#> 1 a 2
#> 2 a NA
#> 3 b 5
#> 4 b NA
#> 5 c 7
#> 6 c NA
让我们从上面的数据框开始。我想填写 col2
,除非 col1
中的值为 a
。解决方案如下所示:
#> # A tibble: 6 x 2
#> col1 col2 col3
#> <chr> <dbl> <dbl>
#> 1 a 2 2
#> 2 a NA NA
#> 3 b 5 5
#> 4 b NA 5
#> 5 c 7 7
#> 6 c NA 7
我的以下尝试不起作用。如何让 tidyr::fill()
在此 if_else()
上下文中工作?
df %>% mutate(col3 = if_else(col1 != "a", fill(col2), col2))
#> Error in UseMethod("fill_") : no applicable method for 'fill_'
#> applied to an object of class "c('double', 'numeric')"
最佳答案
我不认为这是该函数支持的行为。相反,您可以这样做:
df %>%
filter(col1 == "a") %>%
bind_rows(df %>%
filter(col1 != "a") %>%
fill(col2))
col1 col2
<chr> <dbl>
1 a 2
2 a NA
3 b 5
4 b 5
5 c 7
6 c 7
或者,如果您确实需要 col3
,那么您可以使用 zoo
中的 na.locf()
:
df %>%
mutate(col3 = ifelse(col1 != "a", na.locf(col2), col2))
col1 col2 col3
<chr> <dbl> <dbl>
1 a 2 2
2 a NA NA
3 b 5 5
4 b NA 5
5 c 7 7
6 c NA 7
关于r - tidyr `fill()` 可以与 R 中的 if_else() 一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58593107/