英文:
Extract first not NA value from selected columns
问题
我想从一组列中提取第一个非 NA 值。 "第一个" 的定义是根据列的顺序。 示例:
library(tidyverse)
d1 <- tribble(~a, ~x, ~w, ~z,
"s", NA, 1, 2,
"m", 2, 3, 0,
"k", 9, NA, NA,
"o", NA, NA, 4,
"z", NA, NA, NA)
这是一个不起作用的选项 - 因为它只提取了 2 和 9:
d1 %>%
mutate(want = pmap_int(list(x, w, z), ~.x[!is.na(.x)][1]))
想要的结果是:1, 2, 9, 4, NA
。
英文:
I would like to extract the first non NA value from a set of columns. "First" is defined by the order of columns. Example:
library(tidyverse)
d1 <- tribble(~a, ~x, ~w, ~z,
"s", NA, 1, 2,
"m", 2, 3, 0,
"k", 9, NA, NA,
"o", NA, NA, 4,
"z", NA, NA, NA)
That is a not working option - because it only extracts 2 & 9:
d1 %>%
mutate(want = pmap_int(list(x, w, z), ~.x[!is.na(.x)][1] ))
Want is: 1, 2, 9, 4, NA
.
答案1
得分: 3
使用 dplyr::coalesce
,您可以这样做:
library(tidyverse)
d1 |>
mutate(want = coalesce(x, w, z))
#> # A tibble: 5 × 5
#> a x w z want
#> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 s NA 1 2 1
#> 2 m 2 3 0 2
#> 3 k 9 NA NA 9
#> 4 o NA NA 4 4
#> 5 z NA NA NA NA
英文:
Using dplyr::coalesce
you could do:
library(tidyverse)
d1 |>
mutate(want = coalesce(x, w, z))
#> # A tibble: 5 × 5
#> a x w z want
#> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 s NA 1 2 1
#> 2 m 2 3 0 2
#> 3 k 9 NA NA 9
#> 4 o NA NA 4 4
#> 5 z NA NA NA NA
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论