在R中将数据帧转换为隶属网络 [英] converting data frame into affiliation network in R

查看:126
本文介绍了在R中将数据帧转换为隶属网络的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下格式的数据框:

I have a data frame with the following format:

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

我想将此数据帧转换为R格式的联属网络

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

我使用了以下程序:

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

其中A1是数据帧,而a1是从属网络.但是,由于我的数据帧很大,因此上面的程序运行非常慢.有没有一种有效的方法来避免数据转换中的循环?

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?

非常感谢!

推荐答案

如果您的数据名为df,请这样做:

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

这篇关于在R中将数据帧转换为隶属网络的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆