mercredi 14 octobre 2020

fill the blanks in a column with another column, if a different set of columns are matching

I have a question regarding some data I am working with in R. I have two data frames. The second data frame is a list of changes that I want to make in the first data frame.

df1
       date  plot.no      sp1       sp2    weight   tag
1     14oct       06    green                  70     1
2     14oct       05   yellow                  63     2
3     14oct       04      red     red01        41     3
4     14oct       04      red                  41     3
df2
       sp1      sp2 
1    green   orange  
2      red     blue  
3   yellow   yellow   

If a color of df1$sp1 matches a color in df2$sp1, I would like to fill the corresponding blank cells of df1$sp2 with what is written in the corresponding cells in the df2$sp2. I don't want to overwrite what is already written in df1$sp2.

I tried merging the dataframes by the sp1 column think that that would add the sp2 column to the corresponding entries, but that didn't seem to work.

This is what I want the data frame to look like after the changes:

df.final
       date  plot.no      sp1       sp2    weight   tag
1     14oct       06    green    orange        70     1
2     14oct       05   yellow    yellow        63     2
3     14oct       04      red     red01        41     3
4     14oct       04      red      blue        41     3

Not sure if this should be done with ifelse statements or loops instead?

Aucun commentaire:

Enregistrer un commentaire