Apply a mathematical operation on rows of an R data frame stored in a list.


To apply a mathematical operation such as multiplication, division, subtraction and addition on rows of an R data frame stored in a list, we can use apply function.

For Example, if we have a list called LIST that contains a data frame df with two columns say X and Y and we want to add rows of df then we can use the command mentioned below −

apply(df,1,function(x) x["X"]+x["Y"])

Check out the Example given below to understand how it can be done.

Example

Following snippet creates a sample data frames: −

x1<-rnorm(20)
y1<-rnorm(20)
df1<-data.frame(x1,y1)
x2<-rpois(20,5)
y2<-rpois(20,5)
df2<-data.frame(x2,y2)
List<-list(df1,df2)
List

The list of these data frames is as follows −

[[1]]
          x1         y1
 1 -1.5731993  0.11244718
 2 -1.9456438  0.20793065
 3  0.6984799  1.21806315
 4 -0.9044348  1.15796145
 5 -1.3220205  1.51746076
 6 -2.4595593  1.19932839
 7  0.7052369  0.46857422
 8  0.2257025  1.19549664
 9  1.7703144 -0.90544795
10 -1.1280562  1.19661179
11  1.3450602  1.08065271
12 -0.4960736  0.82348313
13  0.2703035 -0.89962056
14  1.6588146  0.01264785
15  0.9652318  0.70363607
16 -1.6510901  1.53432591
17 -0.5948874  0.46737082
18 -0.3386917 -0.01119323
19  0.6576946  0.14457605
20  0.5898998 -1.75455914

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

To divide row values in x1 by y1 for each row in df1 on the above created data frames, add the following code to the above snippet −

x1<-rnorm(20)
y1<-rnorm(20)
df1<-data.frame(x1,y1)
x2<-rpois(20,5)
y2<-rpois(20,5)
df2<-data.frame(x2,y2)
List<-list(df1,df2)
apply(df1,1,function(x) x["x1"]/x["y1"])

Output

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

 [1] -13.9905627 -9.3571763   0.5734349 -0.7810578 -0.8712057 -2.0507805
 [7]  1.5050697   0.1887939  -1.9551808 -0.9427085  1.2446739 -0.6024089
[13] -0.3004639   131.1538482 1.3717771 -1.0761013 -1.2728382  30.2586086
[19]  4.5491260  -0.3362097

To multiply row values in x2 with y2 for each row in df2 on the above created data frames, add the following code to the above snippet −

x1<-rnorm(20)
y1<-rnorm(20)
df1<-data.frame(x1,y1)
x2<-rpois(20,5)
y2<-rpois(20,5)
df2<-data.frame(x2,y2)
List<-list(df1,df2)
apply(df2,1,function(x) x["x2"]*x["y2"])

Output

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

[1] 45 12 60 4 7 12 12 20 54 12 54 20 10 12 24 36 48 24 16 12

Updated on: 09-Nov-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements