r - 结合两个配对 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))
解决方案
我认为使用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
推荐阅读
- javascript - 如何在不删除孩子的情况下更改 span 的文本?
- c++ - unexpected not all control paths return a value?
- html - 为什么我的文本是垂直对齐的,而不是水平对齐的?
- javascript - 您如何调整谷歌广告的大小并将其保存在 DIV 中并使其不大于 DIV?
- java - 打印 x & y 坐标图并显示绘图点的 Java 程序
- c# - Unity NavMeshAgent 与玩家碰撞时开始转向不同的方向
- react-native - 在 React-Native 应用程序上加载巨大的 SVG 的最佳方式是什么?
- vba - 我们如何在 Excel VBO BO 中为 BluePrism 创建“检查成功”输出?
- asp.net - 为什么我无法将图像填充到 ASP.NET MVC 应用程序中的表中?
- firebase - Firebase signOut() 问题(颤振)