How to randomly replace values in an R data frame column?

R ProgrammingServer Side ProgrammingProgramming

The random replacement values in an R data frame column can be done with the help of sample function along with nrow function and single square subsetting.

For Example, if we have a data frame called df that contains a columns say X and we want to randomly replace 5 values in X with 1.5 then we can use the below given command −

df$X[sample(nrow(df),5)]<-1.5

Example 1

Following snippet creates a sample data frame −

x<-rnorm(20)
df1<-data.frame(x)
df1

The following dataframe is created

         x
 1  0.6329624
 2 -0.1499087
 3  1.4854089
 4 -1.1517261
 5  0.1337649
 6  0.2561524
 7 -0.5776149
 8 -0.7255745
 9 -0.5188515
10 -1.1959642
11  0.8444887
12 -0.4273016
13 -1.3380255
14 -0.3433049
15 -0.7926529
16  0.2302148
17 -0.3378159
18 -1.1405204
19  1.2611400
20  0.3000847

To randomly replace 10 values in x with 0 on the above created data frame, add the following code to the above snippet −

x<-rnorm(20)
df1<-data.frame(x)
df1$x[sample(nrow(df1),10)]<-0
df1

Output

If you execute all the above given snippets as a single program, it generates the following Output −

        x
 1  0.6329624
 2 -0.1499087
 3  0.0000000
 4 -1.1517261
 5  0.1337649
 6  0.2561524
 7 -0.5776149
 8  0.0000000
 9 -0.5188515
10  0.0000000
11  0.8444887
12 -0.4273016
13  0.0000000
14  0.0000000
15  0.0000000
16  0.0000000
17  0.0000000
18  0.0000000
19  1.2611400
20  0.0000000

Example 2

Following snippet creates a sample data frame −

y<-rpois(20,10)
df2<-data.frame(y)
df2

The following dataframe is created

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

To randomly replace 15 values in y with 1 on the above created data frame, add the following code to the above snippet −

y<-rpois(20,10)
df2<-data.frame(y)
df2$y[sample(nrow(df2),15)]<-1
df2

Output

If you execute all the above given snippets as a single program, it generates the following Output −

    y
 1  1
 2  1
 3  1
 4  1
 5  1
 6  1
 7  1
 8  1
 9  1
10  1
11  1
12  1
13 14
14  1
15 15
16 11
17 12
18  1
19  1
20 11
raja
Updated on 10-Nov-2021 07:41:44

Advertisements