2013-10-08 145 views
1

我的变量的矢量:which.min()与随机抽样

x<-runif(1000,0,1) 

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

x[which.min(x)]

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

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

+1

但是,如果他们都一样为什么你关心哪一个返回? –

+1

@ SimonO101,我猜这是'which.min'返回的位置,而不是价值? – A5C1D2H2I1M1N2O1R2T1

+0

@AnandaMahto谢谢(希望)清理,我已经添加了答案,如果是这样的话。 –

回答

3

使用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] 
+0

我会建议相同,但你需要在此工作。请记住,当你从一个单一的数字样本(例如'样本(300,1)' – A5C1D2H2I1M1N2O1R2T1

+0

@AnandaMahto良好的抓更新中... –

+1

确定什么'sample'做你现在可以有我的票:) – A5C1D2H2I1M1N2O1R2T1

2

另一个类似的方法,但一个不使用if是做一个sampleseq_along匹配的值。

这里有两个例子。 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