We can group by ‘A’, ‘B’ and select the first non-NA element across
other columns
library(dplyr)
df1 %>%
group_by(A, B) %>%
summarise(across(everything(), ~ .[order(is.na(.))][1]), .groups="drop")
-output
# A tibble: 1 x 8
# A B C D E F G H
# <chr> <chr> <int> <int> <int> <int> <int> <lgl>
#1 time place 1 2 3 4 5 NA
Or with coalesce
library(purrr)
df1 %>%
group_by(A, B) %>%
summarise(across(everything(), ~ reduce(., coalesce)), .groups="drop")
data
df1 <- structure(list(A = c("time", "time", "time"), B = c("place",
"place", "place"), C = c(NA, 1L, NA), D = c(NA, NA, 2L), E = c(3L,
NA, NA), F = c(4L, NA, NA), G = c(NA, 5L, NA), H = c(NA, NA,
NA)), class = "data.frame", row.names = c(NA, -3L))
solved Multiples rows to one row in R [closed]