Home > Net >  If values are duplicated in column A but not in column B, how can I change values in column B so the
If values are duplicated in column A but not in column B, how can I change values in column B so the

Time:12-08

I have a dataframe like this

same_id <- data.frame(scientific_name = c("ABIES BIFOLIA", 
"ABIES LASIOCARPA", "ABIES LASIOCARPA", "ABIES MENZIESII", "PINUS LASIOCARPA"),
                      id = c(1, 1, 1, 2, 1),
                      cover = c(80, 60, 20, 10, 20))

Which looks like this

   scientific_name id cover
1    ABIES BIFOLIA  1    80
2 ABIES LASIOCARPA  1    60
3 ABIES LASIOCARPA  1    20
4  ABIES MENZIESII  2    10
5 PINUS LASIOCARPA  1    20

If different scientific names are associated with the same id, I want to replace all the scientific names in the id group with the first value, keeping other values as they are.

This is my desired end result

   scientific_name id cover
1    ABIES BIFOLIA  1    80
2    ABIES BIFOLIA  1    60
3    ABIES BIFOLIA  1    20
4  ABIES MENZIESII  2    10
5    ABIES BIFOLIA  1    20

CodePudding user response:

Using dplyr:

library(dplyr)

same_id %>% 
  group_by(id) %>% 
  mutate(scientific_name = first(scientific_name))
  •  Tags:  
  • r
  • Related