Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201919

How to replace NA value with previous non NA value given to same ID

$
0
0

I'm working in R and am using data.table. I have a data set that looks like this:

ID   country_id    weight
1    BGD           56
1    NA            57
1    NA            63
2    SA            12
2    NA            53
2    SA            54

If the value in country_id is NA I need to replace it with a non-na country_id value given to the same ID. I would like the data set to look like this:

ID   country_id    weight
1    BGD           56
1    BGD           57
1    BGD           63
2    SA            12
2    SA            53
2    SA            54

This data set contains millions of IDs, so fixing each ID manually is not an option.

Thanks for your help!

Edit: Solved!

I used this code: dt[, country_id := country_id[!is.na(country_id)][1], by = ID]


Viewing all articles
Browse latest Browse all 201919

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>