I'm trying to see if I can use dplyr's coalesce or something like it to combine rows in the same way coalesce combines columns.
I found some other similar posts but none that answer my question.
Here's a toy sample:
df <- read.table(sep = "|", header = F, stringsAsFactors = F, text =
"a|NA|NA|d|NA
NA|b|NA|NA|e
a|NA|c|NA|e
1|2|3|4|5
1|2|3|4|5
1|2|3|4|5
1|2|3|4|5")
> df
V1 V2 V3 V4 V5
1 a <NA> <NA> d <NA>
2 <NA> b <NA> <NA> e
3 a <NA> c <NA> e
4 1 2 3 4 5
5 1 2 3 4 5
6 1 2 3 4 5
7 1 2 3 4 5
I would like to combine rows 1, 2 and 3 into a single row that I can use as headers. The output should look like this:
V1 V2 V3 V4 V5
1 a b c d e
2 1 2 3 4 5
3 1 2 3 4 5
4 1 2 3 4 5
5 1 2 3 4 5
I was hoping something like this would work:
df %>%
rowwise() %>%
coalesce(1,2,3) %>%
slice(-c(1:2))
This worked but it feels clunky:
df %>%
slice(1:3) %>%
fill(everything(), .direction = "down") %>%
slice(3) %>%
bind_rows(df %>%
slice(-c(1:3)))
I'd like something more straightforward and elegant.