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

R ProgrammingServer Side ProgrammingProgramming

#### Artificial Intelligence : The Future Of Programming

15 Lectures 54 mins

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### C Programming from scratch- Master C Programming

Best Seller

60 Lectures 8 hours

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 −

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
Updated on 10-Nov-2021 07:41:44