You could try a solution with na.omit
. This function will remove NA
within each group. Assuming your data frame is df
...
In base R:
aggregate(. ~ Id,
data = df,
FUN = function(x) {
y = na.omit(x)
y[length(y) == 0] <- NA
y
},
na.action = "na.pass")
Note that y[length(y) == 0]
is included to ensure cases like Id
5 and var2
are NA
and not character(0)
.
With dplyr
:
library(dplyr)
df %>%
group_by(Id) %>%
summarise(across(everything(), ~ first(na.omit(.))))
Using first
will include the first value within the group after NA
removed. across(everything())
will apply this method to all columns.
With data.table
:
library(data.table)
setDT(df)[, lapply(.SD, na.omit), by = Id]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…