How to create a repeated values column with each value in output selected randomly in R data frame?


To generate a repeated values column with each value in output selected randomly in R data frame, we can use replicate function. The replicate function will repeat the vector values up to the number of times we want and each value will be randomly selected. To understand how it works, check out the below examples.

Example 1

Using replicate function to create a data frame df with normal random variable column of size 25 −

x<-replicate(25,rnorm(1))
df<-data.frame(x)
df

Output

      x
1  -0.26328537
2  -1.00037955
3  -1.41223385
4   0.91023814
5  -0.85441197
6  -0.02750725
7  -0.49752777
8   0.28294846
9  -1.57283687
10 -0.08043108
11  1.10330290
12  1.87867775
13  1.12583717
14 -0.02388753
15 -0.10188550
16 -0.39874679
17 -1.64919986
18  0.09986504
19 -0.37351112
20  1.61446219
21  1.98338695
22 -0.06839704
23 -0.53683398
24  0.32234184
25  1.48537413

Example 2

Using replicate function to create a data frame dat with exponential random variable column of size 25 −

y<-replicate(25,rexp(1))
dat<-data.frame(y)
dat

Output

       y
1  0.78963761
2  0.69131189
3  3.27911093
4  0.03684389
5  0.65045614
6  2.35530602
7  2.55195765
8  2.25505896
9  0.17827180
10 2.65156010
11 0.79994460
12 1.98539920
13 0.64341737
14 0.44108365
15 1.26718882
16 1.96954975
17 1.50026457
18 0.16052116
19 2.08137533
20 0.44562416
21 3.26818741
22 0.30758178
23 2.35556834
24 0.39836906
25 2.29180449

Example 3

Using replicate function to create a data frame data with poisson random variable column of size 25 −

z<-replicate(25,rpois(1,25))
data<-data.frame(z)
data

Output

   z
1  22
2  21
3  36
4  26
5  24
6  25
7  22
8  25
9  33
10 18
11 25
12 17
13 19
14 28
15 27
16 28
17 19
18 26
19 19
20 15
21 17
22 24
23 25
24 23
25 32

Updated on: 10-Nov-2021

823 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements