Creating edge list with additional variables in R

妖精的绣舞 提交于 2020-01-06 23:51:37

问题


I have data like this:

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

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

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"?


回答1:


Try

  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



回答2:


I feel like already solved this once, but here's a possible solution using data.table and it's new (v >= 1.9.5) tstrsplit function

library(data.table)
setDT(df1)[, if(.N > 1) tstrsplit(combn(as.character(item),
              2, paste, collapse = ";"), ";"),
            .(ID, sex)]

#     ID    sex V1 V2
# 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


来源:https://stackoverflow.com/questions/28449118/creating-edge-list-with-additional-variables-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!