我正在寻找R的复制功能,并意识到我为不同的群体生成相同的数字。
我认为replicate
应该生成不同的数字,因为rnorm
在replicate
内再次进行。
这是我意识到的,
df <- data.frame(y=rep(replicate(2,c(rnorm(5,0.27,0.01), rnorm(5,0.24,0.01))),times=2),
gr = rep(seq(1,2),each=20))
> df
y gr
1 0.2658965 1
2 0.2635201 1
3 0.2610166 1
4 0.2673029 1
5 0.2679714 1
6 0.2507213 1
7 0.2494571 1
8 0.2467961 1
9 0.2373631 1
10 0.2319886 1
11 0.2875434 1
12 0.2739122 1
13 0.2796172 1
14 0.2782527 1
15 0.2646329 1
16 0.2260419 1
17 0.2188761 1
18 0.2521573 1
19 0.2458168 1
20 0.2286136 1
21 0.2658965 2
22 0.2635201 2
23 0.2610166 2
24 0.2673029 2
25 0.2679714 2
26 0.2507213 2
27 0.2494571 2
28 0.2467961 2
29 0.2373631 2
30 0.2319886 2
31 0.2875434 2
32 0.2739122 2
33 0.2796172 2
34 0.2782527 2
35 0.2646329 2
36 0.2260419 2
37 0.2188761 2
38 0.2521573 2
39 0.2458168 2
40 0.2286136 2
两组的数字都是一样的!我们如何解决这个问题?
答案 0 :(得分:1)
我相信rep
导致了这个问题。尝试:
data.frame(y = do.call(c, replicate(n = 4,
expr = c(rnorm(5,0.27,0.01), rnorm(5,0.24,0.01)),
simplify = FALSE)),
gr = rep(seq(1,2),each=20))
OR
data.frame(y = do.call(c, lapply(1:2, function(i)
c(rnorm(5, 0.27, 0.01), rnorm(5, 0.27, 0.01),
rnorm(5,0.24,0.01), rnorm(5,0.24,0.01)))),
gr = rep(seq(1,2),each=20))
OR
data.frame(y = do.call(c, lapply(1:2, function(i)
c(replicate(n = 2, rnorm(5, 0.27, 0.01)),
replicate(n = 2, rnorm(5,0.24,0.01))))),
gr = rep(seq(1,2),each=20))