How to generate random numbers with sequence and store in a data frame column in R?

R ProgrammingServer Side ProgrammingProgramming

To generate random numbers with sequence and storing them in a data frame column, we can use sample function with seq. For example, if we want to create a data frame column having random sequence of values of size 50 between 1 to 100 by considering every tenth value then we can use the command

df<-data.frame(x=sample(seq(from=1,to=100,by=10),size=50,replace=TRUE))

Check out the below examples to understand how it works.

Example

 Live Demo

df1<-data.frame(x=sample(seq(from=10,to=50,by=5),size=20,replace=TRUE))
df1

Output

   x
1  20
2  15
3  10
4  45
5  45
6  35
7  35
8  50
9  35
10 50
11 10
12 35
13 10
14 25
15 20
16 45
17 50
18 10
19 40
20 10

Example

 Live Demo

df2<-data.frame(y=sample(seq(from=0,to=100,by=5),size=20,replace=TRUE))
df2

Output

   y
1  85
2  60
3  30
4  65
5  65
6  65
7  35
8  25
9  15
10 70
11 5
12 10
13 65
14 50
15 30
16 75
17 100
18 90
19 15
20 65

Example

 Live Demo

df3<-data.frame(z=sample(seq(from=0,to=100,by=10),size=20,replace=TRUE))
df3

Output

     z
1   60
2   30
3   80
4   20
5   80
6  100
7  100
8   30
9   10
10  80
11  100
12   10
13   70
14 100
15  20
16  50
17  70
18  30
19  50
20  20
raja
Published on 16-Mar-2021 12:46:03
Advertisements