在R中使用其他变量创建边列表 [英] Creating edge list with additional variables in R
本文介绍了在R中使用其他变量创建边列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的数据:
ID=c(rep("ID1",3), rep("ID2",2), "ID3", rep("ID4",2))
sex=c(rep("male",3), rep("female",2), "female", rep("male",2))
item=c("a","b","c","a","c","a","b","a")
df1 <- data.frame(ID,sex,item)
df1
ID sex item
1 ID1 male a
2 ID1 male b
3 ID1 male c
4 ID2 female a
5 ID2 female c
6 ID3 female a
7 ID4 male b
8 ID4 male a
并且我需要像这样的边缘:
and I would need it as edges like this:
head(nodes)
ID sex V1 V2
1 ID1 male a b
2 ID1 male b c
3 ID1 male a c
4 ID2 female a c
5 ID4 male b a
有了@akrun的友善帮助,我可以通过以下方式获取V1和V2列:
With @akrun's kind help I could get the V1 and V2 columns with this:
lst <- lapply(split(item, DG), function(x) if(length(x) >=2) t(combn(x,2)) else NULL)
nodes=as.data.frame(do.call(rbind,lst[!sapply(lst, is.null)]) )
但是我怎么也可以从原始df中获取" ID和其他一些变量(性别,年龄等),并在节点"中将它们作为性别"等列?
but how could I also "take along" ID and some other variables (sex, age etc) from the original df and have them as "sex" etc columns in "nodes"?
推荐答案
尝试
res <- do.call(rbind,lapply(split(df1, df1$ID), function(x) {
m1 <- if(length(x$item)>=2)
t(combn(as.character(x$item),2))
else NULL
if(!is.null(m1))
data.frame(ID=unique(x$ID), sex=unique(x$sex), m1)}))
row.names(res) <- NULL
res
# ID sex X1 X2
#1 ID1 male a b
#2 ID1 male a c
#3 ID1 male b c
#4 ID2 female a c
#5 ID4 male b a
这篇关于在R中使用其他变量创建边列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文