How to apply multiple AND conditions to a data frame in R?

R ProgrammingServer Side ProgrammingProgramming

To apply multiple conditions to a data frame, we can use double and sign that is &&. For example, if we have a data frame called df that contains three columns say x, y, z and we want to add a value to all columns if first element in z equals to 5 then it can be done by using the command −

if(df$x && df$y && df$y == 5){
   df$x = df$x+10
   df$y = df$y+10
   df$z = df$z+10
}

Example1

Consider the below data frame −

 Live Demo

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

Output

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

Adding 10 to each column of df1 if first element in column 3 is equal to 5 −

if(df1$x1 && df1$x2 && df1$x3 == 5){
   + df1$x1=df1$x1+10
   + df1$x2=df1$x2+10
   + df1$x3=df1$x3+10
   + }
df1


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

Example2

 Live Demo

y1<-rnorm(20)
y2<-rnorm(20)
df2<-data.frame(y1,y2)
df2

Output

         y1          y2
1  -0.60985060  -1.45276610
2   0.80395413   2.06049252
3  -0.12743614  -1.03176509
4   0.05681372   1.56884539
5  -1.05750863   0.23016019
6  -0.23227935  -0.60140044
7   0.85412909  -0.85129323
8  -1.10052209   0.52922611
9  -0.97370660   1.08355421
10 -0.29749358  -0.04810183
11  1.50965424   0.29086647
12  0.11498843  -1.42433231
13  1.95463083  -0.94930405
14 -0.12241118   0.68882049
15  2.11266281  -0.70163806
16 -2.79657925  -1.17756299
17 -0.39618443  -1.60277178
18 -2.38109125   0.25505674
19 -0.84519632   0.39521130
20  0.46643806   0.04849672
if(df2$y1 && df2$y2 == 2){
 + df2$y1=df2$y1+10
 + df2$y2=df2$y2+10
 + }
df2
      y1           y2
1  -0.60985060  -1.45276610
2   0.80395413   2.06049252
3  -0.12743614  -1.03176509
4   0.05681372   1.56884539
5  -1.05750863   0.23016019
6  -0.23227935  -0.60140044
7   0.85412909  -0.85129323
8  -1.10052209   0.52922611
9  -0.97370660   1.08355421
10 -0.29749358  -0.04810183
11  1.50965424   0.29086647
12  0.11498843  -1.42433231
13  1.95463083  -0.94930405
14 -0.12241118   0.68882049
15  2.11266281  -0.70163806
16 -2.79657925  -1.17756299
17 -0.39618443  -1.60277178
18 -2.38109125   0.25505674
19 -0.84519632   0.39521130
20  0.46643806   0.04849672
raja
Published on 06-Mar-2021 16:32:45
Advertisements