简体   繁体   English

R:如何在给定条件的情况下生成序列seq()?

[英]R: How to generate a sequence seq() given a condition?

I just discovered R and I am trying to work with it. 我刚发现R,并且正在尝试使用它。

Here is what I am trying to achieve: 这是我要实现的目标:

I have a vector of numbers, x, between 50 and 100 and with a size of 250 observations. 我有一个数字x的向量,介于50到100之间,大小为250个观察值。

x = sample(seq(50, 100), 250, repeat = T)

Now, I want to generate another vector of numbers, y, between 0 and 100, which is the same size as vector x such that each element in y is less than or equal to its equivalent in x. 现在,我想生成另一个介于0到100之间的数字y的向量,该向量的大小与向量x的大小相同,以使y中的每个元素小于或等于x中的等效元素。

That is to say that if x[1] is 76, for example, the highest value y[1] could attain when generated is 76. But it could definitely be any other value below 76. In other words and more generally, I want vector y to be generated in such a way that y[i] <= x[i]. 就是说,例如,如果x [1]为76,则生成时可以达到的最大值y [1]为76。但是它肯定可以是低于76的任何其他值。换句话说,更广泛地说,我想要向量y以y [i] <= x [i]的方式生成。

I hope I have made my request clearer. 希望我的要求更加明确。

Thank you very much! 非常感谢你!

y <- x -1 # ...........................

 y <- sapply( x, function(x) runif(n=1, max=x))
 y
 [1]  7.2713788 30.0008063 42.5205775  0.9271717 10.7114456 39.5199145  7.4109775
 [8] 28.3464373 28.5840101 34.0654033 15.0675028 50.2836294 45.9031794 13.5931005
[15] 43.2751738 17.0560824  3.1507491 25.7619129 12.3391448 22.6203684 51.3334810
[22] 37.0481703 33.4733277 37.1304850 26.7984406 66.3844126 40.2775918 47.6379024
[29] 16.2480595 66.8358384 33.3513161 60.2673874 65.6204462 45.6951960  1.5729434
[36] 20.4850357  0.1345737 84.5334203 19.7997451 53.8025623 48.5528486  8.8992123
[43] 90.9651742 28.3584167 41.7728159 46.4790641 17.8129578 83.1906415 37.5114353
[50] 89.5685501 85.2499600

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

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