【发布时间】:2019-01-17 18:16:17
【问题描述】:
我已经创建了一个网络,并且有兴趣让节点拥有基于我最初的dataframe 的属性。例如,我的dataframe 将每个节点显示为一定数量的关键字,但这是我在创建网络的过程中丢失的信息。在这个阶段,我有兴趣将其归因于每个节点,以便稍后进行进一步分析。
图表示例:
g <- graph.formula(4506-8974, 8974-6345, 7842-4653, 4653-6345, 7842-8974)
V(g)$name <- c("4506", "8974", "6345", "7842", "4653")
额外的困难是我的dataframe 采用matrix 的形式(尽管技术上仍然是dataframe)。行是节点,列是关键字。我希望列(即关键字)成为每个节点的属性:V(g)$keyword。如果 element = 1,则显示为属性,如果 element = 0,则不考虑。
有谁知道该怎么做?我应该使用ifelse 函数吗?此外,我认为重要的是不要混淆节点 ID 的顺序,否则可能会将关键字属性赋予错误的节点。
df <- data.frame("agriculture" = c(0,1,0,0,0), "arts" = c(0,0,0,1,0), "banks" = c(1,0,1,0,0),
"cities" = c(0,0,0,1,0), "companies" = c(0,0,0,0,1))
rownames(df) <- c("4506", "8974", "6345", "7842", "4653")
NodeID agriculture arts banks cities companies
4506 0 0 1 0 0
8974 1 0 0 0 0
6345 0 0 1 0 0
7842 0 1 0 1 0
4653 0 0 0 0 1
V(g)$keyword <- keyword based on if the element = 1 for each node
我希望的结果是:
V(g)$keyword[1]
[1] "banks"
V(g)$keyword[4]
[4] "arts" "cities"
【问题讨论】: