Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining rows based on the id in R

My data,

Id|date1|date2   
1|2008-10-01|NA        
1|NA|2008-10-02     
1|NA|2008-10-03     
2|2008-10-02|NA
2|NA|2008-10-03

I want output this way,

Id|date1|date2|date3    
1|2008-10-01|2008-10-02|2008-10-03        
2|2008-10-02|2008-10-03 

I tried using aggregate and dcast but they are making date into numeric format and na's are still not avoided.

like image 558
Knight Avatar asked Jun 29 '15 18:06

Knight


People also ask

How do I combine two rows with the same value in R?

To merge rows having same values in an R data frame, we can use the aggregate function.

How do I combine data rows in R?

To merge two data frames (datasets) horizontally, use the merge() function in the R language. To bind or combine rows in R, use the rbind() function. The rbind() stands for row binding.

How do I combine data values in R?

The simplest way to group together values is with the function c() . Feel free to refer to this function however you like, but the words concatenate, combine, and collect are all good options.


1 Answers

You could do this quite easily using data.table though it will get more complicated if the number of non-missing values isn't equal between the columns

library(data.table)
setDT(df)[, lapply(.SD, na.omit), by = Id]
#   Id      date1       date2
# 1:  1 2008-10-02 2008-10-02 
# 2:  2 2008-10-02 2008-10-02 
like image 169
David Arenburg Avatar answered Sep 18 '22 01:09

David Arenburg