Calculate difference between columns of R DataFrame
Last Updated :
26 Jan, 2022
Generally, the difference between two columns can be calculated from a dataframe that contains some numeric data. In this article, we will discuss how the difference between columns can be calculated in the R programming language.
Approach
- Create a dataframe and the columns should be of numeric or integer data type so that we can find the difference between them.
- Extract required data from columns using the $ operator into separate variables. For example, we have two columns then extract individual columns into separate variables.
- Then perform the minus operation for the difference between those columns.
- Finally, print the result.
Example 1 :
R
df= data.frame (num= c (1,2,3,4),num1= c (5,4,3,2))
a=df$num
b=df$num1
print (df)
print (b-a)
|
Output :
Example 2 :
R
df= data.frame (num= c (1.9,2.9,3.4,5.6,9.8),
num1= c (6.3,7.7,8.0,9.3,10.9))
print (df)
a=df$num
b=df$num1
print (b-a)
|
Output :
Example 3 :
R
df= data.frame (num= c (1,2,3,4,5),
num1= c (6,7,8,9,10))
a=df$num
b=df$num1
print (df)
print (b-a)
|
Output :
Share your thoughts in the comments
Please Login to comment...