0

In df I would like to replace the NA values with the non-NA value for each id

id<-c(1,1,1,1,2,2,2)
price<-c(NA,20,NA,NA,NA,NA,5)
df<-data.frame(id,price)

 id    price
  1       NA
  1       20
  1       NA
  1       NA
  2       NA
  2       NA
  2        5

The output should ideally look like:

id      price
  1       20
  1       20
  1       20
  1       20
  2        5
  2        5
  2        5

Any help would be appreciated.

AliCivil
  • 2,003
  • 6
  • 28
  • 43
  • 1
    `df$price <- ave(df$price, df$id, FUN=function(x) { x[is.na(x)] <- mean(x, na.rm=TRUE); x} )` – jogo Sep 11 '19 at 07:32
  • `tidyr::fill` in both the directions. `df %>% group_by(id) %>% fill(price, .direction = "up") %>% fill(price)` – Ronak Shah Sep 11 '19 at 07:34
  • Possible duplicate https://stackoverflow.com/questions/40040834/replace-na-with-previous-or-next-value-by-group-using-dplyr – Ronak Shah Sep 11 '19 at 07:42
  • Possible duplicate of [Replace NA with previous or next value, by group, using dplyr](https://stackoverflow.com/questions/40040834/replace-na-with-previous-or-next-value-by-group-using-dplyr) – jogo Sep 11 '19 at 07:49

1 Answers1

2

Using data.table:

library(data.table)
setDT(df)
df[, price := price[!is.na(price)], id]
df

#    id price
# 1:  1    20
# 2:  1    20
# 3:  1    20
# 4:  1    20
# 5:  2     5
# 6:  2     5
# 7:  2     5
s_baldur
  • 29,441
  • 4
  • 36
  • 69