结合两个配对ID

时间:2019-10-25 02:35:49

标签: r

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))

1 个答案:

答案 0 :(得分:1)

我认为可以使用 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