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.
To merge rows having same values in an R data frame, we can use the aggregate function.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With