Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

r - How do I subset/filter a data.frame by coordinates

I am trying to subset a data.frame (A) containing X= lon/y = lat coordinates and z= elevation in meters. I have thousands of these elevation points, and I would like to extract 160 of them to use. For these 160 I also have the X= lon/y = lat stored in a different data.frame (B)

My questions is how do I filter or subset the data.frame A so that I can only see the elevation points of the points stored in data.frame (B)

Data.frame (A)           Data.frame (B)

    X    Y      Z           X     Y     
 1.  -7.47 5.88  200        -7.47 5.88 
 2.  -8.88 4.55  123        -3.11  9.11  
 3.  -6.32 3.33  233        -8.33  2.44  
 4.  -5.44 2.33  133        -9.21   6.32 
 5.  -4.21 1.22  433
 6.  -3.11  9.11  111
 7.  -2.56  10.12 453
 8.  -9.21   6.32 325
 9.  -8.33  2.44  712
 10. -11.11 5.55  333

So ideally what I would like as a result would be

data.frame (C)

      X    Y      Z
 1.  -7.47 5.88  200 
 2.  -3.11  9.11  111
 3.  -8.33  2.44  712 
 4.  -9.21   6.32 325

Could you please give me some suggestions? Much appreciated!

Kamilla (excuse my ineptness I am quite new to this)

question from:https://stackoverflow.com/questions/65861915/how-do-i-subset-filter-a-data-frame-by-coordinates

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use inner_join() function from dplyr package:

df1 <- data.frame(x = c(-7.47, -8.88, -6.32, -5.44, -4.21, -3.11, -2.56, -9.21, -8.33, -11.11), 
                  y = c(5.88, 4.55, 3.33, 2.33, 1.22, 9.11, 10.12, 6.32, 2.44, 5.55), 
                  z = c(200, 123, 233, 133, 433, 111, 453, 325, 712, 333))

df2 <- data.frame(x = c(-7.47, -3.11, -8.33, -9.21), 
                  y = c(5.88, 9.11, 2.44, 6.32))
library(dplyr)
inner_join(df1, df2)
Joining, by = c("x", "y")
      x    y   z
1 -7.47 5.88 200
2 -3.11 9.11 111
3 -9.21 6.32 325
4 -8.33 2.44 712

If you want to do this without using dplyr:

df1[(df1$x %in% df2$x) & (df1$y %in% df2$y), ]

NOTE: Please provide a reproducible data example next time. You should have defined df1 and df2 as in my answer and not let me do it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...