【问题标题】:which.min() with random samplingwhich.min() 随机抽样
【发布时间】:2013-10-08 11:03:26
【问题描述】:

我有一个变量向量:

x<-runif(1000,0,1)

我想选择具有最低值的元素:

x[which.min(x)]

默认情况下,which.min(x) 将返回满足此条件的第一个元素,但是,可能会出现多个相同低的元素。

有没有办法从这些值中采样并只返回一个?

【问题讨论】:

  • 但是如果它们都是一样的,你为什么要关心返回哪一个呢?
  • @SimonO101,我猜是which.min返回的是位置,而不是值?
  • @AnandaMahto 感谢(希望)澄清这一点,如果是这样的话,我已经添加了一个答案。
  • 您可能还想看看nnet

标签: r


【解决方案1】:

使用which 找到所有等于向量最小值的元素的索引并随机采样一个(除非最小值出现一次 - 然后我们可以返回它)。

# Find indices of minima of vector
ids <- which( x == min(x) )

#  If the minimum value appear multiple times pick one index at random otherwise just return its position in the vector
if( length( ids ) > 1 )
  ids <- sample( ids , 1 )

#  You can use 'ids' to subset as per usual
x[ids]

【讨论】:

  • 我也打算提出相同的建议,但你需要努力解决这个问题。记住 sample 从单个数字中采样时的作用(例如 sample(300, 1)
  • 像往常一样:x==min(x) 对浮点数不安全。推荐abs(x-min(x)) &lt; tiny_value
【解决方案2】:

另一种类似但不使用if 的方法是使用seq_along 匹配的值执行sample

这里有两个例子。 x1 有多个最小值。 x2 只有一个。

## Make some sample data
set.seed(1)
x1 <- x2 <- sample(100, 1000, replace = TRUE)
x2[x2 == 1][-1] <- 2 ## Make x2 have just one min value

## Identify the minimum values, and extract just one of them.
y <- which(x1 == min(x1))
y[sample(seq_along(y), 1)]
# [1] 721

z <- which(x2 == min(x2))
z[sample(seq_along(z), 1)]
# [1] 463

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-31
    • 2013-08-17
    • 1970-01-01
    相关资源
    最近更新 更多