我有这个tibble
library(tidyverse)
data_frame(first = c("a", NA, "b"),
second = c(NA, "b", NA),
third = c("a", NA, NA))
我想逐行使用coalesce()
来抓取非NA的值。
所需的输出将是第一个非NA值的向量,我们可以找到从左到右逐行检查数据帧
[1] "a" "b" "b"
答案 0 :(得分:4)
将do.call
与coalesce
:
do.call(coalesce, df)
# [1] "a" "b" "b"
do.call
按顺序将df
中的列传递给coalesce
,因此相当于coalesce(df$first, df$second, df$third)
。
df <- data_frame(
first = c("a", NA, "b"),
second = c(NA, "b", NA),
third = c("a", NA, NA)
)