How to aggregate characters strings by group in R?

Viewed 130

I have a web scraping data frame with different elements from some documents. I need to aggregate by the frist column, cause it identifies the document. Other columns are the kinds of elements from the text, with a lot of NA values. I want aggregate to make a row for each document with all elements. I've this:

DocID ElementA ElementB
1 A1 NA
1 NA B1
2 A2 NA
2 NA B2
3 A3 NA
3 NA B3

And I want to get:

DocID ElementA ElementB
1 A1 B1
2 A2 B2
3 A3 B3
1 Answers

An option is to group by 'DocID', fill the columns 'ElementA', 'ElementB' with adjacent non-NA elements and get the distinct rows

library(dplyr)
library(tidyr)
df1 %>%
   group_by(DocID) %>%
   fill(ElementA, ElementB, .direction = "downup") %>%
   ungroup %>%
   distinct

-output

# A tibble: 3 x 3
#  DocID ElementA ElementB
#  <int> <chr>    <chr>   
#1     1 A1       B1      
#2     2 A2       B2      
#3     3 A3       B3

data

df1 <- structure(list(DocID = c(1L, 1L, 2L, 2L, 3L, 3L), ElementA = c("A1", 
NA, "A2", NA, "A3", NA), ElementB = c(NA, "B1", NA, "B2", NA, 
"B3")), class = "data.frame", row.names = c(NA, -6L))


  
Related