重复行但数字不同
Repeating the rows but with different numbers
我查看了 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
两组的人数完全一样!我们如何解决这个问题?
我认为 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))
或
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))
或
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))
我查看了 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
两组的人数完全一样!我们如何解决这个问题?
我认为 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))
或
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))
或
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))