【问题标题】:How to find the position of the sampled element?如何找到采样元素的位置?
【发布时间】:2019-05-07 11:08:52
【问题描述】:

我已经定义了一个向量,

x<-rep(10,times=10)

并运行示例函数,

set.seed(42)
sample(x,1,replace=TRUE)

当然,它会显示 10 的结果,但我想知道这个采样元素在原始向量 x 中的位置,从那里元素被采样出来。我们如何找到它?此外,有什么方法可以用任何其他数字替换该采样元素?

【问题讨论】:

  • 如果你想知道被采样元素的索引,为什么不从索引集中采样(并使用采样索引)而不是直接从向量中采样?
  • 如果您只对位置感兴趣而不对元素感兴趣,为什么不使用sample(1:length(x), 1)

标签: r sample


【解决方案1】:

一种解决方法是命名x 的元素:

x <- rep(10,times=10)
names(x) <- letters[seq_along(x)]
which(names(x) == names(sample(x,1,replace=TRUE)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-26
    • 2010-11-28
    • 2015-08-14
    • 2011-02-26
    • 1970-01-01
    • 2010-10-15
    • 2016-01-30
    • 2022-06-19
    相关资源
    最近更新 更多