How to change row values based on column values in an R data frame?


Changing row values based on column values means that we want to change the row values for a particular column if the column values satisfy a certain condition. For example, if we have a data frame called df that contains a column say x and we want to set all the values in x to 5 if they are greater than 5 then it can be done as df[df$x>5,]<-5.

Example1

Consider the below data frame −

Live Demo

> x1<-rpois(20,1)
> x2<-rpois(20,5)
> df1<-data.frame(x1,x2)
> df1

Output

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

Changing values in x1 to 2 if they are greater than 2 −

> df1[df1$x1>2,]<-2
> df1

Output

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

Example2

Live Demo

> y1<-rnorm(20,5,1)
> y2<-rnorm(20,5,0.3)
> df2<-data.frame(y1,y2)
> df2

Output

         y1       y2
1  4.826729 5.433352
2  3.530581 5.266034
3  5.811061 4.582195
4  5.620806 5.745011
5  4.799159 5.323772
6  5.287042 5.111730
7  5.128602 5.192648
8  4.372339 5.014256
9  5.078192 5.175813
10 4.392499 5.231547
11 4.983643 5.390611
12 4.168723 4.620990
13 2.691008 4.932305
14 3.715511 4.455306
15 3.674058 5.136752
16 5.439690 5.082509
17 6.393444 4.139432
18 5.220288 5.201459
19 4.695000 4.960111
20 5.925427 5.013475

Changing values in y1 to 3 if they are greater than 3 −

> df2[df2$y1>3,]<-3
> df2

Output

         y1       y2
1  3.000000 3.000000
2  3.000000 3.000000
3  3.000000 3.000000
4  3.000000 3.000000
5  3.000000 3.000000
6  3.000000 3.000000
7  3.000000 3.000000
8  3.000000 3.000000
9  3.000000 3.000000
10 3.000000 3.000000
11 3.000000 3.000000
12 3.000000 3.000000
13 2.691008 4.932305
14 3.000000 3.000000
15 3.000000 3.000000
16 3.000000 3.000000
17 3.000000 3.000000
18 3.000000 3.000000
19 3.000000 3.000000
20 3.000000 3.000000

Updated on: 05-Mar-2021

358 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements