r中子图的平均值

时间:2014-08-31 15:12:39

标签: r igraph

数据看起来像这样

library(igraph)
From <- c(1,2,3,4,5,6,7,8)
To <- c(NA,1,2,3,2,NA,6,7)
Value<- c(1,0,0.5,0.5,0,-1,-1,-0.5)
Data <- data.frame(From,To, Value)
Network <- graph.data.frame(Data[,c("From","To")])
Network<- Network - "NA"
plot(Network)

现在我想知道它们所处的部分图的AverageValue以及初始的Dataframe。 最后它应该是这样的:

From <- c(1,2,3,4,5,6,7,8)
To <- c(NA,1,2,3,2,NA,6,7)
Value<- c(1,0,0.5,0.5,0,-1,-1,-0.5)
AverageTreeValue<- c(0.4,0.4,0.4,0.4,0.4,-0.833,-0.833,-0.833)
FinalData <- data.frame(From,To, Value, AverageTreeValue)

1 个答案:

答案 0 :(得分:3)

您可以使用clusters函数计算图表中的已连接组件,aggregate计算每个群集的平均值,并merge将两者合并在一起:< / p>

Data$group <- clusters(Network)$membership
(FinalData <- merge(Data, aggregate(Value~group, Data, mean), by="group"))
#   group From To Value.x    Value.y
# 1     1    1 NA     1.0  0.4000000
# 2     1    2  1     0.0  0.4000000
# 3     1    3  2     0.5  0.4000000
# 4     1    4  3     0.5  0.4000000
# 5     1    5  2     0.0  0.4000000
# 6     2    6 NA    -1.0 -0.8333333
# 7     2    7  6    -1.0 -0.8333333
# 8     2    8  7    -0.5 -0.8333333

或者,您可以使用match执行合并,并对生成的列的名称进行更多控制:

groups <- clusters(Network)$membership
means <- aggregate(Value~group, data.frame(Value=Data$Value, group=groups), mean)
Data$AverageTreeValue <- means$Value[match(groups, means$group)]
Data
#   From To Value AverageTreeValue
# 1    1 NA   1.0        0.4000000
# 2    2  1   0.0        0.4000000
# 3    3  2   0.5        0.4000000
# 4    4  3   0.5        0.4000000
# 5    5  2   0.0        0.4000000
# 6    6 NA  -1.0       -0.8333333
# 7    7  6  -1.0       -0.8333333
# 8    8  7  -0.5       -0.8333333