我有这个数据框: -
pf = structure(list(Var1 = structure(1:21, .Label = c("1", "2", "3",
"4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15",
"16", "17", "18", "19", "20", "21"), class = "factor"), Freq = c(101L,
61L, 84L, 98L, 56L, 222L, 137L, 103L, 136L, 97L, 77L, 110L, 84L,
88L, 92L, 89L, 86L, 87L, 84L, 71L, 36L), Relative_freq = c(0.0505252626313157,
0.0305152576288144, 0.0420210105052526, 0.0490245122561281, 0.0280140070035018,
0.111055527763882, 0.0685342671335668, 0.0515257628814407, 0.0680340170085043,
0.0485242621310655, 0.0385192596298149, 0.0550275137568784, 0.0420210105052526,
0.0440220110055028, 0.0460230115057529, 0.0445222611305653, 0.0430215107553777,
0.0435217608804402, 0.0420210105052526, 0.0355177588794397, 0.0180090045022511
)), .Names = c("Var1", "Freq", "Relative_freq"), row.names = c(NA,
-21L), class = "data.frame")
现在我想基于这个数据帧创建一个矩阵,它将这些relative_freq存储为边(矩阵单元格)权重。
下面是代码: -
k=5
PF = matrix(data=NA, nrow=k, ncol=k)
for(i in 1:k){
for(j in 1:k){
pf = PageFreq(pf,i,j)
a = pf[[1]]
b = pf[[2]]
PF[i,j] = 2 * a *b/(a + b)
}
}
这是我需要调整的PageFreq函数才能正常工作: -
PageFreq = function(pf,i,j){
a = pf %>% filter(Var1 == i) %>% select(Relative_freq);
b = pf %>% filter(Var1 == j) %>% select(Relative_freq);
c = list(a,b);
return (c)
}
请看正确的方法!谢谢
答案 0 :(得分:0)
下面是工作代码: -
PageFreq = function(pf,i,j){
a = pf %>% filter(Var1 == i) %>% select(Relative_freq);
b = pf %>% filter(Var1 == j) %>% select(Relative_freq);
a1 = a$Relative_freq
b1 = b$Relative_freq
c = list(a1,b1);
return (c)
}
k = 21
PF = matrix(data=NA, nrow=k, ncol=k)
for(i in 1:k){
for(j in 1:k){
pff = PageFreq(pf,i,j)
a = pff[[1]]
b = pff[[2]]
PF[i,j] = 2 * a *b/(a + b)
}
}