Stata - 如何生成随机整数 [英] Stata - How to Generate Random Integers

查看:1713
本文介绍了Stata - 如何生成随机整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Stata并想知道如何生成随机整数(无需替换)。如果我总共有10行,我希望每一行都有一个1到10的唯一整数。在R中,人们可以这样做:

I am learning Stata and want to know how to generate random integers (without replacement). If I had 10 total rows, I would want each row to have a unique integer from 1 to 10 assigned to it. In R, one could simply do:

sample(1:10, 10)

但在Stata中似乎更难做到。从这个Stata页面,我看到:

But it seems more difficult to do in Stata. From this Stata page, I saw:

generate ui = floor((b-a+1)*runiform() + a)

如果我用a = 1和b = 10代替,我会得到一些接近我想要的东西,但它会替换为样品。

If I substitute a=1 and b=10, I get something close to what I want, but it samples with replacement.

在弄清楚这一部分之后,我将如何处理以下皱纹:我的数据成对出现。例如,在10个观察中,有5组2.每组2具有唯一标识符。我如何按随机顺序排列组(而不是观察结果)?数据看起来像这样:

After getting that part figured out, how would I handle the following wrinkle: my data come in pairs. For example, in the 10 observations, there are 5 groups of 2. Each group of 2 has a unique identifier. How would I arrange the groups (and not the observations) in random order? The data would look something like this:

obs   group  mem     value
1     A      x       9345
2     A      y       129
3     B      x       251
4     B      y       373
5     C      x       788
6     C      y       631
7     D      x       239
8     D      y       481
9     E      x       224
10    E      y       585  

obs 是观察号。 group 是观察(行)所属的组。 mem 是组中的成员标识符。每个组中都有一个 x 和一个 y

obs is the observation number. group is the group the observation (row) belongs to. mem is the member identifier in the group. Each group has one x and one y in it.

推荐答案

第一个问题:

你可以随意改变观察标识符。

You could just shuffle observation identifiers.

set obs 10
gen y = _n 
gen rnd = runiform()
sort rnd 

或在Mata中

jumble(1::10)

第二个问题:有几种方法。这是一个。

Second question: Several ways. Here's one.

gen rnd = runiform() 
bysort group (rnd): replace rnd = rnd[1] 
sort rnd 

一般注释:为了重现性,请事先设置随机数种子。

General comment: For reproducibility, set the random number seed beforehand.

set seed 2803 

或其他什么。

这篇关于Stata - 如何生成随机整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆