R - 将两个不同长度的数据帧比较为两列中的相同值

Kri*_*ina 5 compare r

这是一个关于如何比较具有不同长度的两个不同数据帧的几列的问题.

我有两个不同长度的数据帧(来自receiver1(rec1)和receiver2(rec2)的数据),包含4个不同船只的位置:

rec1 <- data.frame(name = sample (c("Nina", "Doug", "Alli", "Steve"), 20, replace = TRUE), 
                lon = sample (1:20), 
                lat = sample (1:10)
                )    
rec2 <- data.frame(name = sample (c("Nina", "Doug", "Alli", "Steve"), 30, replace = TRUE), 
                lon = sample (1:30),
                lat = sample (1:30)
                )
Run Code Online (Sandbox Code Playgroud)

它们包含不同的名称(船名,两者的名称相同)和经度(lon)以及纬度(纬度)坐标.

我试图比较两个dfs,看看"lon"和"lat"中每个容器匹配多少个值(即两个接收器拾取相同位置的频率)

基本上我试图找出每个接收器有多好以及有多少数据点重叠(例如百分比).

我不确定这是如何做得最好的,我愿意接受任何建议.非常感谢!!!

Kev*_*n M 5

这是一个经过修改和可重现的测试用例以及我的答案.我将测试集设计为包含匹配的组合和不匹配的组合.

rec1 <- data.frame(shipName = rep(c("Nina", "Doug", "Alli", "Steve"), each = 5), 
                lon = rep.int(c(1:5), 4), 
                lat = rep.int(c(11:15), 4)
                )    
rec2 <- data.frame(shipName = rep(c("Nina", "Doug", "Alli", "Steve"), each = 7), 
                lon = rep.int(c(2, 3, 4, 4, 5, 5, 6), 4),
                lat = rep.int(c(12, 13, 14, 14, 15, 15, 16), 4)
                )

print(rec1)
print(rec2)

#Merge the two data frames together, keeping only those combinations that match
m <- merge(rec1, rec2, by = c("shipName", "lon", "lat"), all = FALSE)

print(m)
Run Code Online (Sandbox Code Playgroud)

如果要计算每种组合出现的次数,请尝试以下操作.(有不同的聚合方式.有些方法在这里.下面是我首选的方法,需要你data.table安装.这是一个很棒的工具,所以你可能想安装它,如果你还没有.)

library(data.table)

#Convert to a data table and optionally set the sort key for faster processing
m <- data.table(m)
setkey(m, shipName, lon, lat)

#Aggregate and create a new column called "Count" with the number of
    #observations in each group (.N)
m <- m[, j = list("Count" = .N), by = list(shipName, lon, lat)]

print(m)

#If you want to return to a standard data frame rather than a data table:
m <- data.frame(m)
Run Code Online (Sandbox Code Playgroud)