Alexander
Alexander

Reputation: 4635

Repeating the rows but with different numbers

I was looking R's replicate function and realized that I am producing the same numbers for different groups.

I was thinking that replicate should produce different numbers as it does since rnorm is conducted again inside of replicate.

Here is what I realized,

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

The numbers are just the same in both groups! How can we fix that ?

Upvotes: 1

Views: 63

Answers (1)

d.b
d.b

Reputation: 32548

I believe rep is causing the issue. Try:

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))

Upvotes: 1

Related Questions