1 year ago

#377859

test-img

Anna Dh

R: Merge rows within one Dataframe with different constellation von Data and NAs

I have a dataframe like this:

df <- data.frame(ID=c(1,2,3,3,4,4,5),
                 Name=c("Name1","Name2","Name3", "Name3","Name4", "Name4", "Name5"),
                 Price2012=c(343,767,NA, 43,NA,330, 646),
                 Price2013=c(423,763,35, 0,304,350, 636))

In the third and fourth as well as in the fifth and sixth row, the ID and the Name is identical. However, the values in the two price columns vary. For ID 3, there is a NA for Price2012 while a value of 35 for Price2013, but also a 43 for Price2012 and a 0 for Price2013. For ID 4, there are also two rows, but no zero and one NA.

I want an output like this, where rows which include a NA in Price2012 in one row and a zero in Price2013 in the other row (with the same ID and Name) are merged to one row and where the NA in Price2012 will be replaced by zero only if there are values for all other cells with the same ID and Name.

df_wish <- data.frame(ID=c(1,2,3,4,4,5),
                 Name=c("Name1","Name2", "Name3","Name4", "Name4", "Name5"),
                 Price2012=c(343,767,43,0,330, 646),
                 Price2013=c(423,763,35,304,350, 636))

I tried to use the aggregate function and I tried to get a solution via subsets, but both resulted in errors.

r

merge

rows

na

0 Answers

Your Answer

Accepted video resources