2

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'.

user42485
  • 751
  • 2
  • 9
  • 19
  • 1
    Does this answer your question? [replace NA value with the group value](https://stackoverflow.com/questions/23583739/replace-na-value-with-the-group-value) – Alan Oct 05 '20 at 21:28

2 Answers2

1

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
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
1

We can use match in base R

df$group <- with(df, na.omit(group)[match(value, unique(value))])
akrun
  • 874,273
  • 37
  • 540
  • 662