0

I have two dataframes. df1:

Species Catch by Year
101 2500
101 1759
116 111
139 178

and df2:

code name
101 COD
116 YELLOWTAIL
139 BLUE ANTIMORA
144 CUSK

and I would like to combine both data frames such that the names from df2 replace the Species codes in df1:

Species Catch by Year
COD 2500
COD 1759
YELLOWTAIL 111
BLUE ANTIMORA 178

I considered using a match function to achieve this but I am quite lost. Any help is appreciated.

Fish_Person
  • 107
  • 5

1 Answers1

1
library(dplyr)

df1 <-
structure(list(Species = c(101L, 101L, 116L, 139L), Catch.by.Year = c(2500L, 
1759L, 111L, 178L)), row.names = c(NA, -4L), class = c("tbl_df", 
"tbl", "data.frame"))

df2 <-
structure(list(code = c(101L, 116L, 139L, 144L), name = c("COD", 
"YELLOWTAIL", "BLUE ANTIMORA", "CUSK")), row.names = c(NA, -4L
), class = c("tbl_df", "tbl", "data.frame"))

df1 %>% 
  inner_join(df2,by = c("Species" = "code")) %>% 
  select(-Species) %>% 
  select(Species = name,Catch.by.Year)

# A tibble: 4 x 2
  Species       Catch.by.Year
  <chr>                 <int>
1 COD                    2500
2 COD                    1759
3 YELLOWTAIL              111
4 BLUE ANTIMORA           178
Vinícius Félix
  • 8,448
  • 6
  • 16
  • 32