Reputation: 295
I have data frame with several rows and I need to merge the rows with same ID.
a=read.csv("a.csv")
view(a)
ID Value1 Value2 Value3 Value4 Value5 Value6
1076 2940 NA NA 2 NA NA
1076 2940 1 A- NA 302 549
1109 2940 NA NA 3 NA NA
1109 2940 NA A- NA 700 150
I need the results like
ID Value1 Value2 Value3 Value4 Value5 Value6
1076 2940 1 A- 2 302 549
1109 2940 NA A- 3 700 150
I have already reviewed the answer to a similar problem (Merging rows with shared information). But I am getting an error in the results.
library(dplyr)
f <- function(x) {
x <- na.omit(x)
if (length(x) > 0) paste(x,collapse='-') else NA
}
a_merge <- a %>% group_by(ID)%>%summarise_all(list(f))
But I am getting the following error
Error: Column `Value2` can't promote group 1 to character
Please help.
Upvotes: 3
Views: 160
Reputation: 28675
If you use data.table
you can avoid converting all the columns to lists and only convert the ones where it's required.
library(data.table)
setDT(df)
df[, lapply(.SD, function(x)
if(length(vals <- unique(x[!is.na(x)])) > 1)
list(vals)
else vals),
by = ID]
# ID Value1 Value2 Value3 Value4 Value5 Value6
# 1: 1076 2940 2,1 A- 2 302 549
# 2: 1109 2940 A- 3 700 150
If you're using toString
you can remove the if
and simplify things. This should apply to dplyr also.
df[, lapply(.SD, function(x) toString(unique(x[!is.na(x)]))),
by = ID]
# 1: 1076 2940 2, 1 A- 2 302 549
# 2: 1109 2940 A- 3 700 150
Modified example data (added a case with >1 distinct value)
df <- fread('
ID Value1 Value2 Value3 Value4 Value5 Value6
1076 2940 2 NA 2 NA NA
1076 2940 1 A- NA 302 549
1109 2940 NA NA 3 NA NA
1109 2940 NA A- NA 700 150
')
Upvotes: 1
Reputation: 51582
Here is a base R approach,
setNames(do.call(rbind.data.frame, lapply(split(df, df$ID), function(i)
sapply(i, function(j) j[!is.na(j)][1]))), names(df))
# ID Value1 Value2 Value3 Value4 Value5 Value6
#1 1076 2940 1 A- 2 302 549
#2 1109 2940 <NA> A- 3 700 150
Upvotes: 2
Reputation: 886948
An option would be to create a condition with if/else
to return NA when all the values in the column is NA
or else
get the unique
non-NA elements in a list
library(dplyr)
a %>%
group_by(ID) %>%
summarise_all(list(~ list(if(all(is.na(.))) NA else unique(.[!is.na(.)]))))
# A tibble: 2 x 7
# ID Value1 Value2 Value3 Value4 Value5 Value6
# <int> <list> <list> <list> <list> <list> <list>
#1 1076 <int [1]> <int [1]> <chr [1]> <int [1]> <int [1]> <int [1]>
#2 1109 <int [1]> <lgl [1]> <chr [1]> <int [1]> <int [1]> <int [1]>
EDIT:
1) Wrapped in a list
2) @Gregor's comment - get only the unique
non-NA elements
a <- structure(list(ID = c(1076L, 1076L, 1109L, 1109L), Value1 = c(2940L,
2940L, 2940L, 2940L), Value2 = c(NA, 1L, NA, NA), Value3 = c(NA,
"A-", NA, "A-"), Value4 = c(2L, NA, 3L, NA), Value5 = c(NA, 302L,
NA, 700L), Value6 = c(NA, 549L, NA, 150L)), class = "data.frame", row.names = c(NA,
-4L))
Upvotes: 3