0

So I have a large data set of survey data (surveys 1 to 350 ish) and each survey has a survey site - one of around 70 locations. These surveys all have species records. The problem is there are two datasets. The survey information which has the survey number and location is one dataset. The species records are stored in a different data set (which has over 5000 records) and this data set has the survey number but not the location. I want a way to match the ID of the survey from the survey data set to the species dataset and insert a location column into the species dataset. Preferably without having to manually type a list of each survey location for each survey number. So far I have not been able to do this using dplyr functions like mutate and I am unsure how to write my own function. Here is some dummy data for an example (apologies if my dummy data is terrible I am pretty useless when it comes to making dummy data):

ID<-c(1,2,3,1,2,3,1,2,3,1,2,3)
Species<-c("S1", "S3", "S4", "S6", "S2", "S3", "S4", "S5", "S1", "S2", "S4", "S6")
df1<-data.frame(ID, Species)
df1<-df1[order(df1$ID),]
df1

 ID Species
1   1      S1
4   1      S6
7   1      S4
10  1      S2
2   2      S3
5   2      S2
8   2      S5
11  2      S4
3   3      S4
6   3      S3

ID2<-c(1,2,3)
Location<-c("L1", "L2", "L3")
df2<-data.frame(ID2, Location)
df2

  ID2 Location
1   1       L1
2   2       L2
3   3       L3

So, with this dummy data I would like to use df2 essentially like a key to evaluate df1's ID column and where they match, insert the correct location for all of the rows with that ID. Any ideas?

Jaimie
  • 1
  • What you are describing is a merge. See the linked duplicate question for all the different ways to merge data. You can probably get away with `merge(df1, df2, by.x="ID", by.y="ID2")` or `dplyr::left_join(df1, df2, by=c("ID"="ID2"))` here. – MrFlick Nov 30 '20 at 00:48
  • Thanks! I had already tried the merge function but couldn't get it to work right hence I opened a new question. Your code worked perfectly though! Cheers. – Jaimie Nov 30 '20 at 01:34

0 Answers0