我有一个列表中包含的一些tidygraph对象。我正在尝试计算相同的列(在tidygraph节点数据中)的频率。
例如,
如果我创建一些节点和边缘数据,将它们转换为tidygraph对象,并将它们放在一个列表中,如下所示:
library(tidygraph)
# create some node and edge data for the tbl_graph
nodes <- data.frame(name = c("x4", NA, NA),
val = c(1, 5, 2))
nodes2 <- data.frame(name = c("x4", NA, NA),
val = c(3, 2, 2))
nodes3 <- data.frame(name = c("x4", NA, NA),
val = c(5, 6, 7))
nodes4 <- data.frame(name = c("x4", "x2", NA, NA, "x1", NA, NA),
val = c(3, 2, 2, 1, 1, 2, 7))
nodes5 <- data.frame(name= c("x1", "x2", NA),
val = c(7, 4, 2))
nodes6 <- data.frame(name = c("x1", "x2", NA),
val = c(2, 1, 3))
edges <- data.frame(from = c(1,1), to = c(2,3))
edges1 <- data.frame(from = c(1, 2, 2, 1, 5, 5),
to = c(2, 3, 4, 5, 6, 7))
# create the tbl_graphs
tg <- tbl_graph(nodes = nodes, edges = edges)
tg_1 <- tbl_graph(nodes = nodes2, edges = edges)
tg_2 <- tbl_graph(nodes = nodes2, edges = edges)
tg_3 <- tbl_graph(nodes = nodes4, edges = edges1)
tg_4 <- tbl_graph(nodes = nodes5, edges = edges)
tg_5 <- tbl_graph(nodes = nodes6, edges = edges)
# put into list
myList <- list(tg, tg_1, tg_2, tg_3, tg_4, tg_5)我们可以看到tg、tg_1和tg_2都有相同的name列。类似地,tg_4和tg_5在节点数据中具有相同的name列。
我正在尝试想出一种方法来计算具有相同name列的tidygraph对象的频率。我希望能够返回tidygraph对象的列表,可能会添加另一个列来显示频率。在我的例子中,val列并不重要,所以我想要的输出如下所示:
[[1]]
# A tbl_graph: 3 nodes and 2 edges
#
# A rooted tree
#
# Node Data: 3 × 2 (active)
name frequency
<chr> <dbl>
1 x4 3
2 NA 3
3 NA 3
#
# Edge Data: 2 × 2
from to
<int> <int>
1 1 2
2 1 3
[[2]]
# A tbl_graph: 3 nodes and 2 edges
#
# A rooted tree
#
# Node Data: 3 × 2 (active)
name frequency
<chr> <dbl>
1 x1 2
2 x2 2
3 NA 2
#
# Edge Data: 2 × 2
from to
<int> <int>
1 1 2
2 1 3
[[3]]
# A tbl_graph: 7 nodes and 6 edges
#
# A rooted tree
#
# Node Data: 7 × 2 (active)
name frequency
<chr> <dbl>
1 x4 1
2 x2 1
3 NA 1
4 NA 1
5 x1 1
6 NA 1
# … with 1 more row
#
# Edge Data: 6 × 2
from to
<int> <int>
1 1 2
2 2 3
3 2 4
# … with 3 more rows为了清楚起见,在上面的示例中,包含x4, NA, NA的name列在我的原始对象列表中出现了3次。因此频率计数为3。类似地,等于x1, x2, NA的name列在myList中出现2次,因此它的频率为2...等等。
但是,对于返回频率信息的最佳方式,我愿意接受任何聪明的建议。
发布于 2021-11-17 05:36:05
因为tidygraph和tidyverse配合得很好,所以我们可以直接使用dplyr语法来操作元素。要使频率(可能不是正确的术语)或一系列递减发生,可以使用后跟n()的group_by()。然后,我们可以依靠向量循环来为列表元素的列赋值,这取决于它的索引.y。
freqs <- lapply(myList, function(x){
x %>%
pull(name) %>%
replace_na("..") %>%
paste0(collapse = "")
}) %>%
unlist(use.names = F) %>%
as_tibble() %>%
group_by(value) %>%
mutate(val = n():1) %>%
pull(val)
purrr::imap(l, ~.x %>%
mutate(frequency = freqs[.y]) %>%
select(name, frequency))
[[1]]
# Node Data: 3 x 2 (active)
name frequency
1 x4 3
2 NA 3
3 NA 3
# Edge Data: 2 x 2
from to
<int> <int>
1 1 2
2 1 3
[[2]]
# Node Data: 3 x 2 (active)
name frequency
<chr> <int>
1 x4 2
2 NA 2
3 NA 2
# Edge Data: 2 x 2
from to
<int> <int>
1 1 2
2 1 3
[[3]]
# Node Data: 3 x 2 (active)
name frequency
<chr> <int>
1 x4 1
2 NA 1
3 NA 1https://stackoverflow.com/questions/69998371
复制相似问题