[英]Subset a dataframe by unique combination of values from another dataframe in R
I have a large dataframe A similar to the following and a second one, B, containing only lat/lon values. 我有一个类似于以下内容的大型数据框A,第二个数据框B仅包含经度/纬度值。 What I am trying to do is to subset dataframe A based on the unique combinations of lat/lon from dataframe B. So far, I have tried the following but does not work.
我想要做的是基于数据帧B中经纬度的唯一组合来对数据帧A进行子集设置。到目前为止,我已经尝试了以下操作,但不起作用。 How should I change my code in order to effectively do this?
我应该如何更改代码才能有效地做到这一点?
head(A)
vals time lon lat mo year
1 5 1978-11-01 100 32 01 1988
2 3 1978-11-02 100 45 02 1988
3 3 1978-11-03 100 45 01 1998
4 9 1978-11-04 100 50 05 1998
5 1 1978-11-05 100 60 05 1998
6 4 1978-11-06 100 32 05 1998
A_subset <-subset(A, A[, "lon"] %in% B$lon | A[, "lat"]
%in% B$lat)
Consider running an expand.grid
on data frame B for all combination of unique coordinates. 考虑为唯一坐标的所有组合在数据框B上运行
expand.grid
。 Then merge to data frame A: 然后合并到数据框A:
B_all_combns <- expand.grid(lon = unique(B$lon), lat = unique(B$lat))
A_subset <- merge(A, B_all_combns, by=c("lon", "lat"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.