AliCivil
AliCivil

Reputation: 2053

Replacing NAs with non-NA values by ID

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.

Upvotes: 0

Views: 48

Answers (1)

s_baldur
s_baldur

Reputation: 33488

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

Upvotes: 2

Related Questions