简体   繁体   English

如何在R中生成一个正负分数序列

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

I would like to generate sequences of positives and negatives numbers in a specific interval. 我想在特定间隔内生成正数和负数的序列。 For example, I would like to generate 10 numbers in [0.2,-0.9] without zeros . 例如,我想在[0.2,-0.9]生成10不带零的数字 Here are my tries: 这是我的尝试:

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

All my tries did not give me what I want. 我所有的尝试都没有给我我想要的东西。 The expected output is, for example, 预期的输出例如是

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

Any help, please? 有什么帮助吗?

The answer below adds the new requirement at the end (about not having 0). 下面的答案在末尾添加了新的要求(大约没有0)。

You need seq and to have the numbers in the correct order: 您需要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 

and I recommend sample_n : 我建议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 

Update: 更新:

You mentioned you don't want 0. There are many ways to accomplish this. 您提到您不希望为0。有多种方法可以实现此目的。 The best way probably depends on the set of statistical implications that you prefer if that's important to you. 最好的方法可能取决于对您而言很重要的一组统计含义。 Here are some examples: 这里有些例子:

Example 1 例子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)

Example 2 例子2

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

You could also use a while . 您也可以使用一段while Basically for each element you'd take random samples until there's one that's not == 0 . 基本上,对于每个元素,您都会随机抽样,直到有一个不是== 0样本为止。 That's probably how I would do it to avoid polluting the distributional assumptions. 我可能会这样做,以避免污染分配假设。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM