r - tidyr `fill()` 可以与 R 中的 if_else() 一起使用吗?

标签 r if-statement tidyr

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/

相关文章:

Rblpapi - 将 bdp 与 ISIN/Cusip 一起使用会出现错误

具有多个 IF 条件的 Excel TEXTJOIN

r - 在 RStudio 中拆分扬声器和对话

r - 在R中,如何按data.table中的特定值对列进行排序?

r - 将同义词链接到通用标识符

java - 测试字符串是否包含数组中的任何字符串

powershell - 如何从相同的运行进程中获取 pid 并将输出通过管道传输到 if 语句

r - 创建只有 1 个 ID 列的宽数据

r - 将 tibble 作为带有行名称的矩阵展开

r - 使用 dplyr 和 tidyr 计算小计