Match missing value in a data frame to another value

Viewed 42

I have a data frame with some missing group information. I want to use the value to match to where the identical value is found to assign the group.

df <- data.frame(group = c(NA, 'group1', 'group2'),
                 value = c(0.7, 0.7, 0.3)) 

How can I see where the value of the NA group matches to another group, and set that NA value equal to that group? Here, the NA should be 'group1'.

2 Answers

A base R option using merge + subset

merge(df["value"],subset(df,complete.cases(df)))

which gives

  value  group
1   0.3 group2
2   0.7 group1
3   0.7 group1

We can use match in base R

df$group <- with(df, na.omit(group)[match(value, unique(value))])
Related