从序列创建随机值,但具有随机重复的精确唯一观察数

时间:2017-05-05 13:18:50

标签: r dataframe random unique

我希望从特定的数字序列创建一个9776整数的随机向量,在这种情况下从1到14610,但是唯一的观察数必须等于2444并且每个观察必须随机重复,即不是2444次独特的观察,每次重复4次。

有什么建议吗?

由于

1 个答案:

答案 0 :(得分:1)

我们可以使用rep获取length约9776,然后执行sample

df <- data.frame(x= sample(rep(seq_len(2444), length.out=9776)))
length(unique(df$x))
#[1] 2444

如果我们需要将length.out替换为each,也可以将其替换为

df1 <- data.frame(x= sample(rep(seq_len(2444), each = 4)))
length(unique(df1$x))
#[1] 2444

或者@lmo提到

df <- data.frame(x=sample(c(sample(2444), sample(2444, 9776-2444, replace=TRUE))))

df <- data.frame(x = sample(rep(sample(2444), length.out = 9776)))
length(unique(df$x))
#[1] 2444

head(df$x)
#[1]  858 1505 1631  105   79  268
tail(df$x)
#[1]   51 1545  100 1398 2261  682

更新

使用OP的更新问题

df1 <- data.frame(x=sample(rep(head(sample(14610), 2444), each = 4)))
length(unique(df1$x))
#[1] 2444

UPDATE2

df1 <- data.frame(x = sample(rep(head(sample(14610), 2444), 
                           sample(rep(1:4, length.out=2444))))) 
length(unique(df1$x))
#[1] 2444

table(table(df1$x))

#   1   2   3   4 
#  611 611 611 611 
相关问题