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
# create first dataframe data1= data.frame ( 'name' = c ( 'siva' , 'ramu' , 'giri' , 'geetha' ), 'age' = c (21,23,21,20)) # display print (data1) # create second dataframe data2= data.frame ( 'name' = c ( 'siva' , 'ramya' , 'giri' , 'geetha' , 'pallavi' ), 'marks' = c (21,23,21,20,30)) # display print (data2) print ( "=========================" ) # left join on name column 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
# load the library library ( "dplyr" ) # create first dataframe data1= data.frame ( 'name' = c ( 'siva' , 'ramu' , 'giri' , 'geetha' ), 'age' = c (21,23,21,20)) # display print (data1) # create second dataframe data2= data.frame ( 'name' = c ( 'siva' , 'ramya' , 'giri' , 'geetha' , 'pallavi' ), 'marks' = c (21,23,21,20,30)) # display print (data2) print ( "=========================" ) # left join on name column print ( left_join (data1, data2, by= 'name' )) |
Output:
Please Login to comment...