r中的样本函数在向量中找到第n个最大值

问题描述 投票:0回答:1

我是R语言的初学者,但坚持这个问题:

使用sample()在13到16之间选择一个随机数(称为n)。打印向量中的第n个最小值和第n个最大值。

The 16th smallest value: 0.2325475
The 16th largest value: 0.4879389

我尝试了以下代码:

n <- 13:16
sample(n, replace = T)
r
1个回答
0
投票

我想确认我是否正确理解了这个问题:

  • 选择在13和16之间随机的数字n
  • 然后从数字向量中提取最小的n(th)和最大的n(th)
> # Get randome number between 13 & 16 by runif and round it so we get a round number.
> # I think there are better random function for this but just a quick one here
> number_n <- round(runif(1, min=13, max=16), 0)
> 
> # I just created a random vector here with 100 numbers
> vector_numbers <- runif(100, 0, 1)
> 
> # Sort it so I can get n(th) smallest & n(th) largest by index
> vector_numbers <- sort(vector_numbers)
> #16th smallest
> vector_numbers[number_n]
[1] 0.1794583
> #16th largest
> vector_numbers[100-number_n]
[1] 0.8836753
© www.soinside.com 2019 - 2024. All rights reserved.