user3794143
user3794143

Reputation: 11

For data.frame in R, pulling data from one data frame based on values from another data frame

Sorry if this is really simple, but I've been trying to fin an answer for hours. I have two data frames that contain several columns each, example of similar situation below (actual data frames are very large and cumbersome).

First data frame

    "GPS_ID" "Object_ID" "DBH_cm"
     1        19426       15
     2        9456        9
     3        19887       11
     5        18765       4 
     6        9322        7

And the second data frame

    "Location" "ID"
     block 1    9456
     block 2    18765
     block 2    9322

I need to create a new object that has ONLY the ID's in the second data frame matched with their corresponding DBH_cm's from the first data frame. I thought maybe merging would help, but when I tried it, it just added the Location column to the first data frame.

Upvotes: 0

Views: 126

Answers (2)

akrun
akrun

Reputation: 887213

You can also use inner_join from dplyr. If x and y are the two datasets

 library(dplyr)
 colnames(y)[2] <- colnames(x)[2]
 inner_join(x,y, by="Object_ID")
 #  GPS_ID Object_ID DBH_cm Location
 # 1      2      9456      9  block 1
 # 2      5     18765      4  block 2
 # 3      6      9322      7  block 2

Upvotes: 0

ccapizzano
ccapizzano

Reputation: 1616

If I understand your final output correctly, the merge function should be what you need:

> merge(x,y, by.x = "Object_ID", by.y = "ID")
  Object_ID GPS_ID DBH_cm Location
1      9322      6      7  block_3
2      9456      2      9  block_1
3     18765      5      4  block_2

You can further edit the new data.frame by removing what columns you don't require.

Upvotes: 1

Related Questions