首页 > 解决方案 > 结合两个配对 id

问题描述

df <- tibble(id=c(1,2,3,4,5,6,7,8,9,10),
             x = c( NA, 1,NA, 1, 2,NA, 2,3,3,NA), 
             y = c(1,1,2,2,3,3,4,NA,NA,4))

如果我们有两个对 id(x 和 y),我如何创建具有公共对(z)的整体对 id(y)?我们可以使用nest()吗?

我想得到的数据集是这样的:

df <- tibble(id=c(1,2,3,4,5,6,7,8,9,10),
             x = c( NA, 1,NA, 1, 2,NA, 2,3,3,NA),
             y = c(1,1,2,2,3,3,4,NA,NA,4), 
             z=c(1,1,1,1,2,2,2,3,3,2))

标签: r

解决方案


我认为使用igraph包中的一些聚类方法可以实现这一点:

library(igraph)
vars <- c("x","y")
# make an edge-list of all the relationships between `id` and `x`, and `id` and `y`
el <- cbind(id=df$id, edge=unlist(Map(paste, df[vars], vars, sep=".")))
# drop out any `NA` values that will cause over-grouping
el <- el[!grepl("^NA", el[,"edge"]),]
# create a graph and extract clusters
cl <- clusters(graph.edgelist(el))$membership

# get cluster labels to finalise
df$znew <- cl[match(df$id, names(cl))]
df
## A tibble: 10 x 5
#      id     x     y     z  znew
#   <dbl> <dbl> <dbl> <dbl> <dbl>
# 1  1.00 NA     1.00  1.00  1.00
# 2  2.00  1.00  1.00  1.00  1.00
# 3  3.00 NA     2.00  1.00  1.00
# 4  4.00  1.00  2.00  1.00  1.00
# 5  5.00  2.00  3.00  2.00  2.00
# 6  6.00 NA     3.00  2.00  2.00
# 7  7.00  2.00  4.00  2.00  2.00
# 8  8.00  3.00 NA     3.00  3.00
# 9  9.00  3.00 NA     3.00  3.00
#10 10.0  NA     4.00  2.00  2.00

推荐阅读