3

I have a data frame which looks like the following

Order Location 
1     X
1     NA
2     Y
2     Y
2     NA
3     Z
3     NA
4     Z

I want to replace the NA in column Location with locations pertaining to the same order number. The final result should be

Order Location 
1     X
1     X
2     Y
2     Y
2     Y
3     Z
3     Z
4     Z

How do I achieve this in R using dplyr or any other packages? Thank you.

sk8
  • 170
  • 1
  • 9

1 Answers1

2

We can use fill from tidyr

library(dplyr)
library(tidyr)
df1 %>%
    fill(Location)

If it needs to be grouped by 'Order'

df1 %>%
   group_by(Order) %>%
   fill(Location)
akrun
  • 874,273
  • 37
  • 540
  • 662