我有以下df。
d<- data.frame (type=c("rna","rna","rna"), value = c(1,2,3) )
d2 <- data.frame (type=c("dna","dna"), value = c(20,30) )
d3 <- data.frame (type=c("protein","protein","protein"), value = c(-9.6,300, 1000) )
df <- rbind (d,d2,d3)
df$test = list ( c(0,12), 2, 3, 4,5,6,7, c(20,1) )
type value test
1 rna 1.0 0, 12
2 rna 2.0 2
3 rna 3.0 3
4 dna 20.0 4
5 dna 30.0 5
6 protein -9.6 6
7 protein 300.0 7
8 protein 1000.0 20, 1
我喜欢做的是将列测试从高到低排序。但是,由于测试是一个列表,因此我喜欢做的是仅使用最大值。 例如,第 1 行将使用值 12 和行 20 进行排序。 因此,如果我按降序第 8 行对测试进行排序,将是第一行,然后是第 2 行,依此类推。 当列是数字类型时,我可以排序,但当它是列表时,尤其是当每个元素中有多个值时,我可以排序。 谢谢。
您可以使用sapply(..., max)
从每个向量中提取最大值,然后按其排序:
df %>% arrange(desc(sapply(test, max)))
# type value test
#1 protein 1000.0 20, 1
#2 rna 1.0 0, 12
#3 protein 300.0 7
#4 protein -9.6 6
#5 dna 30.0 5
#6 dna 20.0 4
#7 rna 3.0 3
#8 rna 2.0 2
使用tidyverse
工具:我们可以使用purrr::map_dbl
来获取 'test' 列的max
值,并在arrange(desc())
library(tidyverse)
df %>%
arrange(desc(map_dbl(test, max)))
# type value test
#1 protein 1000.0 20, 1
#2 rna 1.0 0, 12
#3 protein 300.0 7
#4 protein -9.6 6
#5 dna 30.0 5
#6 dna 20.0 4
#7 rna 3.0 3
#8 rna 2.0 2
数据
df <- structure(list(type = structure(c(1L, 1L, 1L, 2L, 2L, 3L, 3L, 3L),
.Label = c("rna", "dna", "protein"), class = "factor"),
value = c(1, 2, 3, 20, 30, -9.6, 300, 1000),
test = list(c(0, 12), 2, 3, 4, 5, 6, 7, c(20, 1))),
row.names = c(NA, -8L), class = "data.frame")
在基 R 中我们可以做
df[order(sapply(df$test, max), decreasing=TRUE), ]
# type value test
# 8 protein 1000.0 20, 1
# 1 rna 1.0 0, 12
# 7 protein 300.0 7
# 6 protein -9.6 6
# 5 dna 30.0 5
# 4 dna 20.0 4
# 3 rna 3.0 3
# 2 rna 2.0 2