Adding a column based on record numbers of a different data frame in R

Viewed 35

I have 2 data frames that look like

sites <- data.frame (name  = c("site_1", "site_2", "site_3","site_4"),
              lat = c("49.99845", "58.30486", "55.70009","53.69490"),
              long=c("-118.6791","-127.8108","-114.3307","-115.3906"),
              closest=c("13","10","5","9")
              )
stations<-data.frame(name=c("stationA","stationB","stationC","stationD",
"stationE","stationF","stationG","stationH","stationI","stationJ","stationK",
"stationL","stationM","stationN","stationO","stationP","stationQ"))

The column called "closest" on the sites DF corresponds to the row number for the stations DF.I want to add another column that has the corresponding name for the stations based on which row number appears on under Sites$closest. So the end result should look like

sites <- data.frame (name  = c("site_1", "site_2", "site_3","site_4"),
          lat = c("49.99845", "58.30486", "55.70009","53.69490"),
          long=c("-118.6791","-127.8108","-114.3307","-115.3906"),
          closest=c("13","10","5","9"),
          stationname=c("stationM","stationJ","stationE","stationI")
          )

My real data set has thousands of rows, so I need something that does not require manual checking. Thank you for any help!

0 Answers
Related