How to apply a manually created function to two columns in an R data frame?


Suppose we created a function that can take two different values at a time then we can apply that function to two columns of an R data frame by using mapply. For example, if we have a manually created function say func that multiply two values then we can apply it to a data frame called df that has two columns x and y by using the below command −

mapply(func,df$x,df$y)
Manually created function named as func:
func <-function(x,y){z<-x*y
   return(z)
}

Example1

Consider the below data frame −

Live Demo

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

Output

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

Applying func on columns x1 and x2 of df1 −

> mapply(func,df1$x1,df1$x2)

Output

[1] 24 35 18 5 56 25 4 48 16 28 30 7 24 30 30 25 12 24 9 12

Example2

Live Demo

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

Output

      y1    y2
1   0.35  1.30
2  -1.67 -1.11
3   0.39 -1.03
4  -1.09  0.60
5   0.05 -0.03
6   0.08  0.60
7   0.47 -0.71
8   2.01  0.33
9  -1.27  0.46
10  0.47 -0.52
11  0.51  1.80
12 -1.14  0.58
13  0.36 -0.59
14 -1.26  0.71
15 -1.13 -0.85
16 -0.66  0.26
17 -0.69  1.00
18  0.01  0.00
19 -1.48  0.72
20  0.70 -0.51

Applying func on columns y1 and y2 of df2 −

> mapply(func,df2$y1,df2$y2)

Output

[1] 0.4550 1.8537 -0.4017 -0.6540 -0.0015 0.0480 -0.3337 0.6633 -0.5842
[10] -0.2444 0.9180 -0.6612 -0.2124 -0.8946 0.9605 -0.1716 -0.6900 0.0000
[19] -1.0656 -0.3570

Updated on: 06-Mar-2021

502 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements