簡體   English   中英

如何在R中生成一個正負分數序列

[英]how to generate a sequences of positive and negative fractional numbers in R

我想在特定間隔內生成正數和負數的序列。 例如,我想在[0.2,-0.9]生成10不帶零的數字 這是我的嘗試:

x <- sample(0.5:-0.9, 20, replace=T)
x
 [1]  0.5  0.5 -0.5  0.5  0.5 -0.5  0.5  0.5 -0.5 -0.5  0.5  0.5  0.5 -0.5  0.5
[16] -0.5  0.5  0.5  0.5 -0.5
x <- sample(0.2:-0.9, 20, replace=T)
x
 [1]  0.2 -0.8  0.2 -0.8 -0.8 -0.8 -0.8 -0.8 -0.8  0.2 -0.8 -0.8 -0.8  0.2 -0.8
[16] -0.8 -0.8 -0.8 -0.8 -0.8
 x <- seq(0.2, -0.9)
 x
[1]  0.2 -0.8

我所有的嘗試都沒有給我我想要的東西。 預期的輸出例如是

0.2, -0.25, 0.3, 0.4, -0.5, 0.5, -0.9, -0.6, 0.7, 0.6

有什么幫助嗎?

下面的答案在末尾添加了新的要求(大約沒有0)。

您需要seq並按正確的順序排列數字:

sample(seq(0.2,from=-0.9,by=.1), 10, replace=T)
 [1] -0.1 -0.6 0.2 0.0 0.0 0.1 0.2 -0.8 -0.7 -0.2 

我建議sample_n

library(dplyr)
sample_n(as_tibble(seq(0.2,from=-0.9,by=.1)), 10, replace=T)
  value <dbl> 1 0.100 2 -0.200 3 0. 4 -0.100 5 0. 6 -0.100 7 -0.600 8 -0.800 9 -0.900 10 -0.900 

更新:

您提到您不希望為0。有多種方法可以實現此目的。 最好的方法可能取決於對您而言很重要的一組統計含義。 這里有些例子:

例子1

x <- sample(seq(0.2,from=-0.9,by=.1), 10, replace=T)

ifelse(x==0, sample(seq(-.1,from=-0.9,by=.1), 1, replace=T), x)

例子2

c(sample(seq(-.1,from=-0.9,by=.1), 5, replace=T),
  sample(seq(.1, 0.2,by=.1), 5, replace=T))

您也可以使用一段while 基本上,對於每個元素,您都會隨機抽樣,直到有一個不是== 0樣本為止。 我可能會這樣做,以避免污染分配假設。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM