gpt4 book ai didi

r - 对最大位于 r 中心的向量进行排序

转载 作者:行者123 更新时间:2023-12-01 07:31:08 24 4
gpt4 key购买 nike

我知道这是一个简单的问题,但我到处搜索,我很确定我的问题没有答案。

我想对一个向量进行排序,其中最大的向量位于中间,当值下降时转到尾部。

例如:

c( 20, 30, 40, 50, 60)

我想要:

c(20, 40, 60, 50, 30 ) or c(30, 50, 60, 40, 20 )

没关系。

谁能给我一个快速的解决方案?

谢谢!

最佳答案

如果您假设您有 2n(n 是一个自然数)个不同的观察值,这将更容易解决。这是一种解决方案:

ints = sample.int(100, size = 30, replace = FALSE)
ints_o = ints[order(ints)]
ints_tent = c(ints_o[seq.int(from = 1, to = (length(ints) - 1), by = 2)],
rev(ints_o[seq.int(from = 2, to = length(ints), by = 2)]))

编辑:

这是处理这两种情况的函数:

makeTent = function(ints) {
ints_o = ints[order(ints)]
if((length(ints) %% 2) == 0) {
# even number of observations
ints_tent = c(ints_o[seq.int(from = 1, to = (length(ints) - 1), by = 2)],
rev(ints_o[seq.int(from = 2, to = length(ints), by = 2)]))
} else {
# odd number of observations
ints_tent = c(ints_o[seq.int(from = 2, to = (length(ints) - 1), by = 2)],
rev(ints_o[seq.int(from = 1, to = length(ints), by = 2)]))
}
return(ints_tent)
}

# test the function
ints_even = sample.int(100, size = 30, replace = FALSE)
ints_odd = sample.int(100, size = 31, replace = FALSE)
makeTent(ints_odd)
makeTent(ints_even)

关于r - 对最大位于 r 中心的向量进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30151676/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com