gpt4 book ai didi

r - 如何在排序和删除元素后恢复向量的原始顺序?

转载 作者:行者123 更新时间:2023-12-04 14:58:22 26 4
gpt4 key购买 nike

我必须删除数值向量中最高的 30 个元素和最低的 30 个元素。我的想法是对向量​​进行排序,然后像这样选择中间的元素:

set.seed(3758)
test.x <- rnorm(1000)
test.x <- sort(test.x)
test.x <- test.x[- seq(length(test.x), length.out = 30)]
test.x <- test.x[- (1:30)]

我的问题是之后我必须恢复向量的原始顺序,但显然它现在比以前少了 60 个元素。所以我不能用 test.x[ord]订单为ord <- order(test.x)原始 test.x 的。有没有办法在不改变我的策略(即排序和删除)的情况下做到这一点?

最佳答案

只需从顺序向量 ord 中删除元素并使用它进行排序

ord <- order(test.x)[-(1:30)]
ordered.x <-test.x[ord]
sub.orig.x <- ordered.x[order(ord)]

例子

set.seed(3758)
test.x <- sample(10)

ord <- order(test.x)[-(1:2)]
ordered.x <-test.x[ord]
sub.orig.x <- ordered.x[order(ord)]

all.equal(test.x[-(1:2)], sub.orig.x)
# TRUE

关于r - 如何在排序和删除元素后恢复向量的原始顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67457190/

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