How to Do a Left Join in R?
In this article, we will discuss how to do a left join in R programming language.
A left join is used to join the table by selecting all the records from the first dataframe and only matching records in the second dataframe.
Method 1: Using merge() function
This function is used to join the dataframes based on the x parameter that specifies left join.
Syntax:
merge(dataframe1,dataframe2, all.x=TRUE)
where,
- dataframe1 is the first dataframe
- dataframe2 is the second dataframe
Example: R program to perform two dataframes and perform left join on name column
R
data1= data.frame ( 'name' = c ( 'siva' , 'ramu' , 'giri' , 'geetha' ),
'age' = c (21,23,21,20))
print (data1)
data2= data.frame ( 'name' = c ( 'siva' , 'ramya' , 'giri' , 'geetha' , 'pallavi' ),
'marks' = c (21,23,21,20,30))
print (data2)
print ( "=========================" )
print ( merge (data1, data2, by= 'name' , all.x= TRUE ))
|
Output:
Method 2: Using left_join
This performs left join on two dataframes which are available in dplyr() package.
Syntax:
left_join(df1, df2, by='column_name')
where
- df1 and df2 are the two dataframes
- column_name specifies on which column they are joined
Example: R program to find a let join
R
library ( "dplyr" )
data1= data.frame ( 'name' = c ( 'siva' , 'ramu' , 'giri' , 'geetha' ),
'age' = c (21,23,21,20))
print (data1)
data2= data.frame ( 'name' = c ( 'siva' , 'ramya' , 'giri' , 'geetha' , 'pallavi' ),
'marks' = c (21,23,21,20,30))
print (data2)
print ( "=========================" )
print ( left_join (data1, data2, by= 'name' ))
|
Output:
Last Updated :
21 Dec, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...