我正试图在变量list
中将唯一元素查找为x
。
唯一的约束是我要首先在列表中找到变量{a
,b
或c
,其变量{{ 1}}元素是最小的,并且在输出的顶部保持不变?
我尝试了一些操作,但是无法实现上述约束:
P.S。。我的目标是实现一个处理较大列表的功能/循环结构。
max
答案 0 :(得分:2)
#Find which element in the list has smallest max.
smallest_max <- which.min(sapply(x, max))
#Rearrange the list by keeping the smallest max in first place
#followed by remaining ones
new_x <- c(x[smallest_max], x[-smallest_max])
#Apply the Map function
new_x[-1] <- Map(setdiff, new_x[-1], new_x[-length(new_x)])
new_x
#$a
#[1] 1 2 3 4 5
#$b
#[1] 6 7
#$c
#[1] 8 9
我们可以将其包装在一个函数中,然后使用它
keep_smallest_max <- function(x) {
smallest_max <- which.min(sapply(x, max))
new_x <- c(x[smallest_max], x[-smallest_max])
new_x[-1] <- Map(setdiff, new_x[-1], new_x[-length(new_x)])
new_x
}
keep_smallest_max(x)
#$a
#[1] 1 2 3 4 5
#$b
#[1] 6 7
#$c
#[1] 8 9