R:如何根据频率为网络创建权重?



我有一个边缘列表(2 列(,我想创建一个第 3 列,根据数据中每个单词的提及次数为每个节点添加权重。

请参阅附加我的数据。

例如:"石油"坏"天然气"多次出现,我想为每次出现相同的值时添加值"1"(并删除多行(。

.dat

这种情况的简单解决方案就是使用table

#create some sample data
set.seed(1)
node1<-rep("oil drilling", 20)
node2<-sample(c("gas", "frack", "pollute", "good"),20,replace=T)
edglst<-data.frame(node1, node2)              
head(edglist,10)
node1   node2
1  oil drilling   frack
2  oil drilling   frack
3  oil drilling pollute
4  oil drilling    good
5  oil drilling     gas
6  oil drilling    good
7  oil drilling    good
8  oil drilling pollute
9  oil drilling pollute
10 oil drilling     gas
#use table to get a dataframe with one row per combination and its frequency
as.data.frame(table(edglst))
node1   node2 Freq
1 oil drilling   frack    5
2 oil drilling     gas    4
3 oil drilling    good    6
4 oil drilling pollute    5

编辑:如果您有一些可能的数据中没有出现的节点组合,您可能还需要删除一些 0,在这种情况下

x<-as.data.frame(table(edglst))
x<-x[!x$Freq==0,]

我不想输入您的数据,所以我将用一些生成的数据来说明。

set.seed(1234)
x = sample(LETTERS[1:6], 20, replace=TRUE)
y = sample(letters[1:6], 20, replace=TRUE)
dat = data.frame(x,y)

可以从plyr包中的count函数获取所需的计数。

library(plyr)
count(dat)
x y freq
1  A b    1
2  A d    1
3  B b    4
4  B e    1
5  B f    2
6  D a    3
7  D b    2
8  D e    2
9  E c    1
10 F b    1
11 F d    1
12 F e    1

最新更新