converting data frame into affiliation network in R

一个人想着一个人 提交于 2020-01-02 08:06:42

问题


I have a data frame with the following format:

name workplace
a     A
b     B
c     A
d     C
e     D
....

I would like to convert this data frame into an affiliation network in R with the format

    A B C D ...
a   1 0 0 0
b   0 1 0 0
c   1 0 0 0
d   0 0 1 0
e   0 0 0 1
...

and I used the following program:

for (i in 1:nrow(A1)) {  
  a1[rownames(a1) == A1$name[i],
     colnames(a1) == A1$workplace[i]] <- 1
}

where A1 is the data frame, and a1 is the affiliation network. However, since I have a large data frame, the above program runs very slow. Is there an efficient way that avoids looping in data conversion?

Thank you very much!


回答1:


If your data called df just do:

as.data.frame.matrix(table(df))
#   A B C D
# a 1 0 0 0
# b 0 1 0 0
# c 1 0 0 0
# d 0 0 1 0
# e 0 0 0 1



回答2:


May be this also helps:

 m1 <- model.matrix(~0+workplace, data=dat)
 dimnames(m1) <- lapply(dat, unique)
 as.data.frame(m1)
 #  A B C D
 #a 1 0 0 0
 #b 0 1 0 0
 #c 1 0 0 0
 #d 0 0 1 0
 #e 0 0 0 1


来源:https://stackoverflow.com/questions/25780309/converting-data-frame-into-affiliation-network-in-r

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