Replace NA with values from another row in another column

Hello everyone,
I would like to replace the NA contained in a variable by the value taken by its duplicate in another line
In fact I would like something like this :
id count model

name
A toyota
A NA
B camry
B NA

and I want input the NA by his ID like this :

name
A toyota
A toyota
B camry
B camry

i have a lot of ID , like seriecode
thank you for your help

Assuming your dataframe is named data, sort it by the id and then use the fill function from tidyr package.

 data <- data  %>%  
arrange(id)  %>%  
tidyr::fill(name, .direction ="down")

2 Likes

thanks for your answer, the problem is that I have a large amount of id and name, I would like to replace the value by the one that its ID takes in another line.
I just tried your code and I get something like this:

id name
Z corolla
A NA
A yaris
C sienna
C NA
C sienna

to this

id name
Z corolla
A corolla
A yaris
C sienna
C sienna
c sienna

here, A should be YARIS
Thank you very much

In that case, add the name column along with id in the arrange()

data <- data  %>%  
                 arrange(id, name)  %>%  
                 tidyr::fill(name, .direction ="down")
2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.