【发布时间】:2017-08-03 13:17:36
【问题描述】:
我确实有一个统计例程,它不喜欢行精确重复(没有 ID)导致空距离。
所以我首先检测我删除的重复项,应用我的例程并合并回留下的记录。
为简单起见,假设我使用rownames 作为 ID/key。
我找到了以下方法来实现我在基础 R 中的结果:
data <- data.frame(x=c(1,1,1,2,2,3),y=c(1,1,1,4,4,3))
# check duplicates and get their ID -- cf. https://stackoverflow.com/questions/12495345/find-indices-of-duplicated-rows
dup1 <- duplicated(data)
dupID <- rownames(data)[dup1 | duplicated(data[nrow(data):1, ])[nrow(data):1]]
# keep only those records that do have duplicates to preveng running folowing steps on all rows
datadup <- data[dupID,]
# "hash" row
rowhash <- apply(datadup, 1, paste, collapse="_")
idmaps <- split(rownames(datadup),rowhash)
idmaptable <- do.call("rbind",lapply(idmaps,function(vec)data.frame(mappedid=vec[1],otherids=vec[-1],stringsAsFactors = FALSE)))
这给了我我想要的,即去重数据(简单)和映射表。
> (data <- data[!dup1,])
x y
1 1 1
4 2 4
6 3 3
> idmaptable
mappedid otherids
1_1.1 1 2
1_1.2 1 3
2_4 4 5
不知道有没有更简单或者更有效的方法(data.table/dplyr接受)。有什么替代方案可以提议吗?
【问题讨论】:
标签: r dataframe duplicates data.table dplyr