How to create a blank column with randomization in an R data frame?


To create a blank column with randomization in an R data frame, we can use sample function and pass the blanks with single space. For example, if we want to create a vector say x that will be added in the data frame can be created by using the command −

x<-sample(c(1," "),20,replace=TRUE)

Check out the below examples to understand how we can create the data frame with columns having blank column.

Example1

 Live Demo

ID<-1:20
x<-sample(c(1," ",3),20,replace=TRUE)
df1<-data.frame(ID,x)
df1

Output

   ID x
1  1  1
2  2  1
3  3  1
4  4  1
5  5  1
6  6
7  7
8  8  3
9  9
10 10 1
11 11 1
12 12 3
13 13 1
14 14 1
15 15 1
16 16 1
17 17 3
18 18 3
19 19 1
20 20

Example2

 Live Demo

S.No<-1:20
y<-sample(c(1," "),20,replace=TRUE)
df2<-data.frame(S.No,y)
df2

Output

  S.No y
1  1   1
2  2
3  3   1
4  4
5  5   1
6  6
7  7   1
8  8   1
9  9   1
10 10  1
11 11  1
12 12
13 13  1
14 14  1
15 15
16 16
17 17  1
18 18
19 19  1
20 20

Updated on: 16-Mar-2021

89 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements