Combine rows by group with differing NAs in each row

Viewed 3133

I can't find an exact answer to this problem, so I hope I'm not duplicating a question.

I have a dataframe as follows

groupid  col1  col2  col3  col4
   1      0     n     NA     2    
   1      NA    NA    2      2

What I'm trying to convey with this is that there are duplicate IDs where the total information is spread across both rows and I want to combine these rows to get all the information into one row. How do I go about this?

I've tried to play around with group_by and paste but that ends up making the data messier (getting 22 instead of 2 in col4 for example) and sum() does not work because some columns are strings and those that are not are categorical variables and summing them would change the information.

Is there something I can do to collapse the rows and leave consistent data unchanged while filling in NAs?

EDIT:

Sorry desired output is as follows:

groupid  col1  col2  col3  col4
   1      0     n     2     2
3 Answers

Another option with just dplyr is just to take the first non-NA value when available. You can do

dd <- read.table(text="groupid  col1  col2  col3  col4
1      0     n     NA     2    
1      NA    NA    2      2", header=T)

dd %>% 
  group_by(groupid) %>% 
  summarise_all(~first(na.omit(.)))
Related