我有一个tidygraph对象列表。我试图根据特定的标准重新排序列表元素。也就是说,我的列表中的每个元素都有一个名为name的列。我试图将具有相同name列的列表元素组合在一起.但是,我也想按其计数的降序(即每个list元素中相等的name列的计数)对它们进行分组。希望我的例子能解释得更清楚。
首先,我创建一些数据,将它们转换为tidygraph对象,并将它们放在一个列表中:
library(tidygraph)
library(tidyr)
# create some node and edge data for the tbl_graph
nodes1 <- data.frame(
name = c("x4", NA, NA),
val = c(1, 5, 2)
)
nodes2 <- data.frame(
name = c("x4", "x2", NA, NA, "x1", NA, NA),
val = c(3, 2, 2, 1, 1, 2, 7)
)
nodes3 <- data.frame(
name = c("x1", "x2", NA),
val = c(7, 4, 2)
)
nodes4 <- nodes1
nodes5 <- nodes2
nodes6 <- nodes1
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_1 <- tbl_graph(nodes = nodes1, edges = edges)
tg_2 <- tbl_graph(nodes = nodes2, edges = edges1)
tg_3 <- tbl_graph(nodes = nodes3, edges = edges)
tg_4 <- tbl_graph(nodes = nodes4, edges = edges)
tg_5 <- tbl_graph(nodes = nodes5, edges = edges1)
tg_6 <- tbl_graph(nodes = nodes6, edges = edges)
# put into list
myList <- list(tg_1, tg_2, tg_3, tg_4, tg_5, tg_6) 因此,我们可以看到,在tidygraph中有6个myList对象。
检查每个元素,我们可以看到有3个对象有相同的name列(即x4,NA,NA).两个对象具有相同的name列("x4", "x2", NA, NA, "x1", NA, NA)。并保留1个对象(x1,x2,NA)。
使用一个小函数获取等名列的计数:
# get a count of identical list elements based on `name` col
counts <- lapply(myList, function(x) {
x %>%
pull(name) %>%
paste0(collapse = "")
}) %>%
unlist(use.names = F) %>%
as_tibble() %>%
group_by(value) %>%
mutate(val = n():1) %>%
slice(1) %>%
arrange(-val)为了清楚起见:
> counts
# A tibble: 3 × 2
# Groups: value [3]
value val
<chr> <int>
1 x4 NA NA 3
2 x4 x2 NA NA x1 NA NA 2
3 x1 x2 NA 1我想根据我的myList对象中的val列重新排列counts中列表元素的顺序。
我想要的输出应该如下所示(我只是手动重新排序):
myList <- list(tg_1, tg_4, tg_6, tg_2, tg_5, tg_3)是否有一种方法可以根据相同的name列的计数来自动重新排序我的列表?
更新:
因此,我尝试的解决方案是执行以下操作:
ind <- map(myList, function(x){
x %>%
pull(name) %>%
replace_na("..") %>%
paste0(collapse = "")
}) %>%
unlist(use.names = F) %>%
as_tibble() %>%
mutate(ids = 1:n()) %>%
group_by(value) %>%
mutate(val = n():1) %>%
arrange(value) %>%
pull(ids)
# return new list of trees
myListNew <- myList[ind]上面的代码将列表元素按name列分组,并返回一个名为ind的索引。然后,我用ind索引索引原始列表,以重新排列我的列表。
但是,我仍然希望找到一种方法,根据每个相同的name变量的总量对新列表进行排序.我还没弄明白呢。
发布于 2021-11-23 01:42:24
经过几个小时的测试,我终于找到了一个可行的解决方案。
ind <- map(myList, function(x){
x %>%
pull(name) %>%
replace_na("..") %>%
paste0(collapse = "")
}) %>%
unlist(use.names = F) %>%
as_tibble() %>%
mutate(ids = 1:n()) %>%
group_by(value) %>%
mutate(val = n():1) %>%
arrange(value)
ind <- ind %>%
group_by(value) %>%
mutate(valrank = min(ids)) %>%
ungroup() %>%
arrange(valrank, value, desc(val)) %>%
pull(ids)
# return new list of trees
myListNew <- myList[ind]上面的代码按name字母顺序排列列表。然后,我按名称分组,并创建另一个列,该列对行进行排序。然后,我可以根据这个变量重新排列行。最后,根据结果进行索引。
https://stackoverflow.com/questions/70067385
复制相似问题