Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 从sankey图表的表中自动获取节点和链接_R_Sankey Diagram - Fatal编程技术网

R 从sankey图表的表中自动获取节点和链接

R 从sankey图表的表中自动获取节点和链接,r,sankey-diagram,R,Sankey Diagram,绘制sankey图需要节点和链接。为了从数据帧中获取节点和链路,可以使用包plyr中的计数函数,并对每个节点使用该函数来计算相邻节点之间的链路,但是否有其他优雅的方法 例如,目标是获取节点和链接: param1 | param2 | param3 | a | b | d | w | c | d | a | b | d | z | c | e | #nodes: nodes =

绘制sankey图需要节点和链接。为了从数据帧中获取节点和链路,可以使用包plyr中的计数函数,并对每个节点使用该函数来计算相邻节点之间的链路,但是否有其他优雅的方法

例如,目标是获取节点和链接:

param1 | param2 | param3 |
a      | b      | d      |
w      | c      | d      |
a      | b      | d      |
z      | c      | e      |

#nodes:
nodes = data.frame("name" = 
c(
a, #node 0
w, #node 1
z, #node 2
b, #node 3
c, #node 4
d, #node 5
e  #node 6
))

#links
links = as.data.frame(matrix(c(
0, 3, 2, # from node 0,  to node 3, freq
1, 4, 1,
2, 4, 1,
3, 5, 2,
4, 5, 1,
4, 6, 1,
),
byrow = TRUE, ncol = 3))
使用igraph软件包:

库(dplyr)
图书馆(igraph)
#示例数据
df1使用igraph软件包:

库(dplyr)
图书馆(igraph)
#示例数据

df1请提供示例数据。我猜igraph软件包会有一个解决方案。请提供示例数据。我猜igraph软件包会有一个解决方案。我还有一个问题,如何避免链接空单元格?如果你能帮忙,那就太好了please@hkn请避免在评论中提出新问题。我还有一个问题,如何避免链接空单元格?如果你能帮忙,那就太好了please@hkn请避免在评论中提出新问题。
library(dplyr)
library(igraph)

# example data
df1 <- read.table(text="
                  param1 param2 param3
                  a b d
                  w c d
                  a b d
                  z c e", header = TRUE, stringsAsFactors = FALSE)

# make graph
g <- graph_from_data_frame(
  rbind(
    setNames(df1[, 1:2], c("from", "to")),
    setNames(df1[, 2:3], c("from", "to"))))


nodes <- data.frame(id = as.numeric(V(g)),
                    name = V(g)$name)
nodes
#   id name
# 1  1    a
# 2  2    w
# 3  3    z
# 4  4    b
# 5  5    c
# 6  6    d
# 7  7    e

links <- as.data.frame(get.edges(g, E(g))) %>%
  group_by(V1, V2) %>%
  summarise(freq = n()) %>% 
  data.frame()

links
#   V1 V2 freq
# 1  1  4    2
# 2  2  5    1
# 3  3  5    1
# 4  4  6    2
# 5  5  6    1
# 6  5  7    1