Some important functions in R

There are some important functions that we are using in Day to day life. I have categories these functions in these categories for understanding.

  • Common function
  • String Function
  • Looping function

Common function

At first, I am dealing with some common functions in R that we use in day to day life during development.

abs() : Calculate absolute value.

 Example:


  
  # abs function
  
amount <- 56.50
absolute_amount <- abs(amount)
print(absolute_amount)
sum(): Calculate the sum of all the values in the data structure.

 Example:


  
  # sum function
  
myList <- c(23,45,56,67)
sumMyList <- sum(myList)
print(sumMyList)
mean() : Calculate arithmetic mean.

 Example:


  
  # mean function
  
myList <- c(23,45,56,67)
meanMyList <- mean(myList)
print(meanMyList)
round() : Round the values to 0 decimal places by default.

 Example:


    
  ############## round function #####################
    
  amount <- 50.97
  print(round(amount));
 
seq(): Generate sequences by specifying the from, to, and by arguments.

 Example:

String Function
    
     # seq() function
     # seq.int(from, to, by)
    
  sequence_data <- seq(1,10, by=3)
  print(sequence_data)
  
rep(): Replicate elements of vectors and lists.

 Example:


    
    #rep exampleString Function
    #rep(x, times)
    sequence_data <- seq(1,10, by=3)  
    repeated_data <- rep(sequence_data,3)
    print(repeated_data)

  
sort(): sort a vector in ascending order, work on numerics.

 Example:


    
    #sort function
    
  data_set <- c(5,3,11,7,8,1)
  sorted_data <- sort(data_set)Functionround
  print(sorted_data)
  
rev(): Reverse the elements in a data structure for which reversal is defined.

 Example:


    
   # reverse function 
    String Function
  data_set <- c(5,3,11,7,8,1)
  sorted_data <- sort(data_set)
  reverse_data <- rev(sorted_data)
  print(reverse_data)
  
str(): Display the structure of any R Object.

 Example:


    
  # str function 
    
  myWeeklyActivity <- data.frame(
    activity=c("mediatation","exercie","blogging","office"),
    hours=c(7,7,30,48)
  )
  print(str(myWeeklyActivity))
  
append() : Merge vectors or lists.

 Example:


    
   #append function 
    
  activity=c("mediatation","exercie","blogging","office")
  hours=c(7,7,30,48)
  append_data <- append(activity,hours)
  print(append_data)
  
is.*(): check for the class of an R Object.

 Example:


    
  #is.*() function
    
  list_data <- list(log=TRUE,
                    chStr="hello"
                    int_vec=sort(rep(seq(2,10,by=3),times=2)))
  print(is.list(list_data))
  
as.*(): Convert an R Object from one class to another.

 Example:


    
  #as.*() function
    
  list_data <- as.list(c(2,4,5))
  print(is.list(list_data))
  

String Function

Now we are discussing some string function that plays a vital role during data cleaning or data manipulation.

These are functions of stringr package.So, before using these functions at first you have to install stringr package.


    
  # import string library
    
  library(stringr)
 
str_trim () : removing white spaces from string.

 Example:


    
    ############### str_trim ####################
    
   trim_result <- str_trim(" this is my string test. ");
   print("Trim string")
   print(trim_result)
 
str_detect(): search for a string in a vector.That returns boolean value.

 Example:


    
  ############### str_detect ####################
    
  friends <- c("Alice","John","Doe")
  string_detect <- str_detect(friends,"John")
  print("String detect ...")
  print(string_detect)
 
str_replace() : replace a string in a vector.

 Example:


    
  ############## str_replace #####################
    
  str_replace(friends,"Doe","David")
  print("friends list after replacement ....");
  print(friends);
 
tolower() : make all lowercase.

 Example:


    
  ############## tolower #####################
    
  myupperCasseString <- "THIS IS MY UPPERCASE";
  print("lower case string ...");
  print(tolower(myupperCasseString));
 
toupper() : make all uppercase.

 Example:


    
  ############## toupper #####################
    
  myupperCasseString <- "My name is Dheeraj";
  print("Upper case string ...");
  print(toupper(myupperCasseString));

 

Lopping

lapply(): Loop over a list and evaluate a function on each element.

 Some important points regarding lapply :

# lapply takes three arguments:

  1. list X
  2. function (or name the function) FUN
  3. … other argumnts

# lapply always returns list, regardless of the class of input.

Example:


    
  ############## lapply example #####################
    
  x <- list(a = 1:5,rnorm(10))
  lapply(x,mean)
 

OutPut:

Anonymous function

Anonymous functions are those functions that have no name.


    
  ############## lapply example #####################
  # Extract first column of matrix 
    
  
  x <- list(a=matrix(1:4,2,2),b=matrix(1:6,3,2))
  lapply(x,function(elt)elt[,1])
 

OutPut:


Use function with lapply


    
  ############## lapply example #####################
  # multiply each element of list with factor
    
  
  multiply <- function(x,factor){
    x * factor
  }

lapply(list(1,2,3),multiply,factor=3)
 

OutPut:

sapply(): Same as lapply but try to simplify the result.

 Example:


    
  ############## sapply example #####################
  # multiply each element of list with factor
    
  multiply <- function(x,factor){
    x * factor
  }
sapply(list(1,2,3),multiply,factor=3)
 

OutPut:

apply() : Apply a function over the margin of an array.

 Example:


    
  ############## apply function #####################
    
  mat1 <- matrix(c(1:10),nrow=5,ncol = 6)
  apply(mat1,2, sum)
 

OutPut:

tapply(): Apply a function over subsets of a vector.

 Example:


    
  ############## tapply function #####################
    
  tapply(mtcars$mpg, list(mtcars$cyl, mtcars$am), mean)
 

OutPut:

mapply():Multivariate version of lapply.

 Example:

Regex with JavaScript Part 3

Match WhiteSpaces

During searching or matching a string. We come across a situation where we need to match spaces in String literals.

For matching spaces in String literals, we use \s  which is a lowercase s.

Example:



/**
* Checking for WhiteSpaces
*/

let checkForWhiteSpaces = "Remove WhiteSpaces from everywhere";
let spaceRegex=/\s/g;
console.log(checkForWhiteSpaces.match(spaceRegex));

OutPut:

Match Non-Whitespace Characters

Previously we had seen for searching white spaces using /s which lowercase s.

Here we are looking for searching Non-Whitespace and that can be done using /S , yes using upperCase s.

Example:



/**
 * Checking for WhiteSpaces
 */

 let checkForWhiteSpaces = "Remove WhiteSpaces from everywhere";
 let spaceRegex=/\s/g;
 console.log(checkForWhiteSpaces.match(spaceRegex));

OutPut:

Specify Upper and Lower Number of Matches

We can specify the lower and upper number of patterns with quantity specifiers.

Quantity specifiers are used within curly brackets ({ and }).

Example:



/**
 * specify upper and lower number of match
 */

let myString ="mmmmmmmk";
let mySecondString ="mk";
// match word "mmmmmmmk" only it has minimum 2 and maximum 4 'm'
let myRegex=/m{2,4}k/;
console.log(myRegex.test(myString));
console.log(myRegex.test(mySecondString));

OutPut:

Specify Only the Lower Number of Matches
Passed

Sometimes we need to match only a lower number of matches.

So To specify a lower number of matches keep the lower number of matches followed by comma in curly bracket ( { n, } ).

where n is a lower number.

Example:



/**
* specify lower number of match
*/

let myString ="pinnnnnnnnnnk";
let mySecondString ="pinnk";
// match word "pinnk" only it has four or more letter of n
let myRegex=/pin{4,}k/;
console.log(myRegex.test(myString));
console.log(myRegex.test((mySecondString)));

OutPut:

Specify Exact Number of Matches

Sometimes we need to specify an exact number of matches.

To specify an exact number of pattern just add that number in curly bracket.

Example:


/**
* specify exact match
*
*/

let myString = "apple";
let mySecondString ="aple";
//p should be appear two times
let myRegex = /ap{2}l/;
console.log(myRegex.test(myString));
console.log(myRegex.test(mySecondString));

OutPut:

Check for All or None

Sometimes we are not sure about the pattern that we are searching for. 

In that case, we use ‘?’ i.e question mark which check for zero or one of the preceding element.

In other words, we can also say that the previous character is optional i.e if that exists then fine and if not then also no problem.

Example:



/**
*
* Check for All or None
*/


let american ="favorite";
let british ="favourite";
let regexPattern = /favou?rite/;

//In this example 'u' is optional
console.log(regexPattern.test(american));
console.log(regexPattern.test(british));

OutPut:

Positive and Negative Lookahead

Lookaheads are patterns in Javascript that tells to Javascript to look-ahead in your string to check for pattern further long.

It can be helpful during searching multiple patterns on the same string.

There are two kinds of Lookaheads :

  • Positive lookahead
  • Negative lookahead

Positive lookahead :

– Look to make sure the element in the search pattern is there, but won’t actually match it.

– Positive Lookahead is used as (?= …)

– Where  the ... is the required part that is not matched.

Negative lookahead :

– Look to make sure the element in the search pattern is not there.

– Negative lookahead is used as (?!...) 

– where the ... is the pattern that you do not want to be there.

Example:



/**
 * lookahead 
 * 
 */

 let myPassword = "ohMyGod123";
 let mySecondPassword ="ohmyGod";
 // regex for a string greater than 5 character long and don't begin with number and have two consequitive numbers
 let myRegex = /^(?=\w{6}(?=\D+\d{2}))/;
 console.log(myRegex.test(myPassword));
 console.log(myRegex.test(mySecondPassword));

OutPut:

Check For Mixed Grouping of Characters Passed

Sometimes we need to match a group of Characters using regular expression.
We can achieve that using () i.e parenthesis.

Example :



/**
*  Mixed grouping Characters
*/

let myString = "laptop";
// check for multiple group of characters
let myRegex = /(lap|Desk)top/;
console.log(myRegex.test(myString));

OutPut:

Reuse Patterns Using Capture Groups

Some patterns are multiple times in a string. Then it is wastage of time to write the pattern multiple times for searching in a string.

Example:



/**
* Reuse patterns using capture Groups
*
*/

let myString ="mummy mummy mummy";
let myRegex = /(\w+)\s\1/;

console.log(myRegex.test(myString));

console.log(myString.match(myRegex));

OutPut:

Use Capture Groups to Search and Replace

We can search and after that replace in string using .replace().

.replace() contains two parameters :

  • First parameter the string that we are searching for
  • Second parameter the string from which we want to replace.

Example:



/**
* Capture group for search andd replace
*/

let myString= "Baba Black Sheep";
// replace Baba Black sheep with Sheep Black Baba
let myRegex = /(\w+)\s(\w+)\s(\w+)/
let myReplacementString= '$3 $2 $1';
console.log(myString.replace(myRegex,myReplacementString));

OutPut:

Remove Whitespace from Start and End

Sometimes we come across the problem that some string contains unwanted whitespaces and that we need to remove these whitespaces from our string.
For removing start and end whitespaces from a string from we use .trim()
method.

Example:



/***
* removing whitespace from string using .trim()
*/

let hello = "   Hello, World!  ";

let result = hello.trim();
console.log(result);

OutPut:

Regex with Javascript Part 2

In the previous post, we have started Regex with JavaScript and discussed some important points of Regex in JavaScript.

In today’s post, we are going to continue with the same topic.

Match Single Character with multiple possibilities

In the previous, we have discussed match pattern where we had dealt with a string pattern (/string/) and wildcard both (/./) and both have its own significance.

Where one finds the exact match and one works with everything.
We can also enhance this search using Character classes.
Character classes allows us to define a group of characters after placing them in square bracket ([ ]).

Example:



/**
 *  range number
 */


 let emailString = "krdheeraj51@gmail.com";
 let regexString = /[a-z@0-9]/g;
 console.log(emailString.match(regexString));

OutPut:

Match letters of Alphabet

In the case of Character match pattern, we can also define a range.
Suppose we have taken all characters from are then we can define our character classes like [a-e];

Example:



/**
* Character classes
*/

let catStr = "cat";
let batStr = "bat";
let ratStr = "rat";
let bgRegex = /[a-e]at/;

console.log(catStr.match(bgRegex));
console.log(batStr.match(bgRegex));
console.log(ratStr.match(bgRegex));

OutPut:

Match Numbers and letters of Alphabet

( – ) is not limited to matching range of character as we have seen previously. But it will also work to match a range of numbers.
For matching a number in between 10 to 15 we can write down like [ 10-15 ].

Example:



/**
*  range number
*/

let emailString = "krdheeraj51@gmail.com";
let regexString = /[a-z@0-9]/g;
console.log(emailString.match(regexString));

OutPut:

Match Single Characters not specified

Till now we have created a set of characters that we want to match.
We can also create a set of characters that we don’t want to match and these types of character sets are known as negated character set.

For using the negated character set we have to use caret character ( ^ ).

Example :

previous post

/**
* Ignore 0 to 9 and all vowel character
*
**/previous post

let quoteSample ="4th Umpire";
//create a regex for Ignore 0 to 9 and all vowel character
let myRegex = /[^0-9^aeiou]/gi;
console.log(quoteSample.match(myRegex));

OutPut:

Match Character that Occurs one or more time

Some times we need to match a group of Character that appears one or more than once.

We can check this case using + character. 

Remember::  In this case Character should be repeated consequently.

It means Character is being repeated one after another.

previous post suppose our String is “abc” and we are using our regex /a+/g then it will return [“a”].

But if our String is like “aabc” then it will return [“a”,”a”].

Example :



/**
* Handle case of matching zero or more Character
*/


let myString = "fuuuuuuuuuuun!!";
let realString = "It is funny time."
let moreString = "Not Interested.";

let myRegex = /fu*/i;

console.log(myString.match(myRegex));
console.log(realString.match(myRegex));
console.log(moreString.match(myRegex));

OutPut:

Match Characters that Occur Zero or More Times

The previous scenario handled the situation of occurring a Character one or more times.
At this time we will handle the same case of occurring a Character that may be occurred zero or more times.
Fo that that purpose we will use * Character.

Example:



/**
* Handle case of matching zero or more Character
*/

let myString = "fuuuuuuuuuuun!!";
let realString = "It is funny time."
let moreString = "Not Interested.";

let myRegex = /fu*/i;

console.log(myString.match(myRegex));
console.log(realString.match(myRegex));
console.log(moreString.match(myRegex));

OutPut:

 

More Post on Regex

Regex with Javascript

 

Regex with Javascript

Regex stands for Regular Expressions also known as Regexp are special strings that represent a search pattern.

For programmers, Regex is like pills that make our task easy.

Regex contains special meaning for some characters that we will explain in further discussion during this post.

Now we will perform some action using functions of Regular Expression.

Match String Using test() method :

As we know that Regex is used to match parts of string.
So, if we want to find “foodie” in the string “Tommy is a foodie.” then we have to use /foodie/ as expression.

Now /foodie/ is our Regex.

Note: Quote marks are not required within regular expression.

JavaScript has multiple ways to use Regex. One of the ways is to use test() method which returns true or false.

Syntax :



regex.test(string)
//return true or false

Example :



var myString = "Codeteaser";
//if our search pattern is teaser from above String
var myRegex = /teaser/;
console.log(myRegex.test(myString));

OutPut:

Match String Literals

We can follow the same approach with String Literals as we have followed previously for matching a string pattern form a strong. In this case, I am taking the same example which I had discussed at the beginning of the post.

Example :


var myStringLterals = "Tommy is a foodie.";
//Search for foodie from string literal
var myRegex =/foodie/;
console.log(myRegex.test(myStringLterals));

OutPut:

But from this approach another form of foodie like Foodie, FOODIE will not match.

Example :


var myStringLterals = "Tommy is a foodie.";
//Search for foodie from string literal
var myRegex =/Foodie/;
console.log(myRegex.test(myStringLterals));

OutPut:

Searching Multiple Option at a time

If we have a string literal “Ronny has a pet cat.” and we are not sure about pet name i.e it is cat or dog or whatever it is. But if we have to add as search pattern on this specific string literal then, in this case, we can follow this approach as shown below.

Example :


var myStringLiteral ="Ronny has a pet cat."
// search for pet name but not sure about pet name
var myRegex = /dog|cat/
console.log(myRegex.test(myStringLiteral));

OutPut:

Note :

We can search multiple patterns using OR or | operator.

Ignore Cases while matching

During matching pattern in a string literal, we had faced a problem while match pattern remains in different cases i.e upperCase (“A”, ”B”, “C” … “Z”) or lowerCases (“a”,”b”,”c” … “z”).
As we had discussed foodie, Foodie or FOODIE are different patterns and these dissimilarities are due to letter case differences.

So, we can ignore letter cases in pattern match using flags in Regex. There are various flags in Regex and ignoring case we will use i flag.

Example:


var myStringLterals = "Tommy is a foodie.";
//Search for foodie from string literal using i flag
var myRegex =/Foodie/i;
console.log(myRegex.test(myStringLterals));

OutPut:

Extract Matches

So till now, we have worked on pattern is existing or not in a String or String Literal. Now we going to extract match pattern from string.
For that purpose, we have to use .match() method.

Example:



/**
* Extrat match pattern
*/

var myExtractStringLiteral="Selena Gomez is a pop Singer.";
// Looking for match pattern
var myRegex =/Singer/;
console.log(myExtractStringLiteral.match(myRegex));

OutPut:

Find more than first

match() method returns the first pattern from a string or string literal.

Example:



/**
* only find first pattern
*/

var myExtractStringLiteral = "Jonny Jonny yes papa";
// Looking for string pattern from a string literal
var myRegex =/Jonny/;
console.log(myExtractStringLiteral.match(myRegex));

OutPut:

But if a string Literal contains multiple times the same pattern then in that case for returning all string pattern we use the g flag as shown in the upcoming example.

Example:



/**
* return all match pattern from a string literal 
*/

var myExtractStringLiteral = "Jonny Jonny yes papa";
// Looking for all match pattern inside String Literal
var myRegex =/Jonny/g;
console.log(myExtractStringLiteral.match(myRegex));

OutPut:

Match anything with wildCard period

Sometimes we don’t know the exact pattern that we want to match. So, in that case, we have to try all possible words that we think for a matching pattern.
And i.e seriously a tough task.
But Regex contains wildCard character: . (dot)
The wildCard character will match anyone character of string.
The wildcard is also called a dot or period.
For example, if we have to match “hug”, “huh”, “hut” then our Regex pattern would be /hu./

Example:



/**
* wildCrad
*/


var myExtractStringLiteral = "I don't like fun during my working period.";
// Searching for fun
var myRegex =/fu./;
//After using dot it will match one character
console.log(myExtractStringLiteral.match(myRegex));

OutPut:

Note: We will discuss more about Regex in further posts.

Joins in SQL for Data Analyst

It is the age of Data and now we Data assume data is more precious than Gold. In Data world SQL is one of the best tool used for Data Analysis.

Types of Joins

Basically, there are four types of JOINS in SQL.

      • CROSS JOIN
      • INNER JOIN

                     –   EQUI JOIN
                                 –  NATURAL JOIN

    • OUTER JOIN

                     –   LEFT JOIN (LEFT OUTER JOIN)
                     –   RIGHT JOIN (RIGHT OUTER JOIN)
                     –   FULL JOIN    (FULL OUTER JOIN)

    • SELF JOIN

For practical implementation of JOINS, we are taking two tables 




# Table Details


Products_dataset:-(product_id,product_category_name,product_name_lenght,product_description_lenght,product_photos_qty,product_weight_g,product_length_cm,product_height_cm,product_width_cm)

product_category_name_translation :- (product_category_name	product_category_name_english)

CROSS JOIN

CROSS JOIN returns cartesian product of two tables.

Cartesian Product

If table A contains m rows and table B contains n rows, then cartesian product of table A and table B will contain m*n rows.
Syntax :




# cross join syntax


SELECT * FROM tableA CROSS JOIN tableB

     or
     
SELECT * FROM tableA,tableB

Example :


SELECT * FROM products_dataset CROSS JOIN product_category_name_translation

OutPut:

INNER JOIN

return all rows from tableA where there are matching values in tableB and all columns from tableA and tableB. If there are multiple matches between tableA and tableB then all matches will return from tableA and tableB on the basis of a specified condition.

And condition has been mentioned in the syntax after the last table.
Syntax:



# Inner join syntax

SELECT * FROM tableA INNER JOIN tableB ON (tableA.x = tableB.y)


or 

SELECT * FROM tableA JOIN tableB ON (tableA.x = tableB.y)

Note: By default, JOIN is considered as INNER JOIN or EQUI JOIN.

Example :



# inner join example

SELECT * FROM products_dataset pds INNER JOIN product_category_name_translation pct
ON pds.product_category_name=pct.product_category_name

OutPut :

LEFT JOIN (LEFT OUTER JOIN) :

return all rows from tableA, and all columns from tableA and tableB. Rows in tableA with no match in tableB will have NA values in the new columns. If there are multiple matches between tableA and tableB, all combinations of the matches are returned.
Syntax :



# left join syntax

SELECT * FROM tableA LEFT JOIN tableB ON (tableA.x = tableB.y)

Example:



#  left join example

SELECT * FROM products_dataset pds LEFT JOIN product_category_name_translation pct

ON pds.product_category_name=pct.product_category_name

OutPut :

RIGHT JOIN (RIGHT OUTER JOIN)

return all rows from tableB, and all columns from tableA and tableB. Rows in tableB with no match in tableA will have NA values in the new columns. If there are multiple matches between tableA and tableB, all combinations of the matches are returned.
Syntax:



# right join syntax

SELECT * FROM tableA RIGHT JOIN tableB ON (tableA.x = tableB.y)

Example:



#  right join example

SELECT * FROM products_dataset pds RIGHT JOIN product_category_name_translation pct
ON pds.product_category_name=pct.product_category_name

OutPut:

Joining data in R using Dplyr

Working with data, Joining is the common operation.

Joining means combine i.e combine the data from two or more than two different sources on the basis of some conditions.

For performing such type of operation in R dplyr is the best option for doing so.

During this post, we will these key points.

  • Types of Joins in R
  • Syntax
  • Joining on DataFrame
  • Joining on tables

Types of Joins

There are six types of Joins in R :

  1. Inner Join (inner_join)
  2. Left Join (left_join)
  3. Right Join (right_join)
  4. Full Join (full_join)
  5. Semi Join (semi_join)
  6. Anti Join (anti_join)

Syntax




# Syntax of Joining in R

Join_type(x,y,by=condition)

/**
  * x: dataframe1/table1
  * y: dataframe2/table2
*/

Joins are basically applied on tables and in case of R files are to be considered as tables.

For a better understanding of joins, we are taking two files 

  1. Product_category_name.csv (product_category_name, product_category_name_english)
  2. product_dataset.csv(product_id,product_category_name,product_name_lenght, product_description_lenght, product_photos_qty, product_weight_g, product_length_cm, product_height_cm, product_width_cm)

You can download these files for your practice my GitHub account

As we know during applying joins on two different datasets or tables we need a common field on the basis of that we can be able to apply a join.

So, in this case, both files contain product_category_name so on the basis of that we can apply to join.

For using a CSV file as a table we are using command 




# read csv file

read.csv(file_name)

So for applying joins on these two files at first, we have to consider these two files as two tables using read.csv() command. As shown below.




# load data


table1 <- read.csv("/home/dheeraj/Desktop/Blog_post/joins_in_r_using_dplyr/dataset/product_category_name.csv") # file location of Product_category_name.csv
table2 <- read.csv("/home/dheeraj/Desktop/Blog_post/joins_in_r_using_dplyr/dataset/products_dataset.csv")   # file location of product_dataset.csv 

Inner Joins

Syntax :



# inner join syntax


inner_join(x,y,by='condition')

Examples :

Select all columns

library(dplyr)
table1 <- read.csv("/home/dheeraj/Desktop/Blog_post/joins_in_r_using_dplyr/dataset/product_category_name.csv") # file location of Product_category_name.csv
table2 <- read.csv("/home/dheeraj/Desktop/Blog_post/joins_in_r_using_dplyr/dataset/products_dataset.csv")   # file location of product_dataset.csv 

appliedInnerJoin <- inner_join(table1,table2,by='product_category_name')

print(head(appliedInnerJoin,n =20))

OutPut:

Select specified columns

If we don’t want to extract all columns then we can select specified columns using select command.

Suppose In this after applying inner join on table1 and table2 we don’t want to extract all columns of these tables but also we want to extract only
product_id.product_category_name_english.

Then we can use select command of dplyr package (for more detail click here) and extract specified columns that we want to extract

Example


library(dplyr)
table1 <- read.csv("/home/dheeraj/Desktop/Blog_post/joins_in_r_using_dplyr/dataset/product_category_name.csv") # file location of Product_category_name.csv
table2 <- read.csv("/home/dheeraj/Desktop/Blog_post/joins_in_r_using_dplyr/dataset/products_dataset.csv")   # file location of product_dataset.csv 

appliedInnerJoin <- inner_join(table1,table2,by='product_category_name')
#select specified column

specified_columns <- select(appliedInnerJoin,product_id,product_category_name_english)
print(specified_columns)

OutPut:

left join

Syntax :


left_join(x,y,by='condition')
 

Example:


library(dplyr)
table1 <- read.csv("/home/dheeraj/Desktop/Blog_post/joins_in_r_using_dplyr/dataset/product_category_name.csv") # file location of Product_category_name.csv
table2 <- read.csv("/home/dheeraj/Desktop/Blog_post/joins_in_r_using_dplyr/dataset/products_dataset.csv")   # file location of product_dataset.csv 
# left join
appliedLeftJoin <- left_join(table1,table2,by='product_category_name')<img src="http://www.krdheeraj.info/wp-content/uploads/2020/01/leftJoin.png" alt="" width="1345" height="579" class="alignnone size-full wp-image-496" />

print(head(appliedLeftJoin,n=10))

OutPut:

right join

Syntax :


right_join(x,y,by='condition')
 

EXample


library(dplyr)
table1 <- read.csv("/home/dheeraj/Desktop/Blog_post/joins_in_r_using_dplyr/dataset/product_category_name.csv") # file location of Product_category_name.csv
table2 <- read.csv("/home/dheeraj/Desktop/Blog_post/joins_in_r_using_dplyr/dataset/products_dataset.csv")   # file location of product_dataset.csv 
# left join
appliedRightJoin <- right_join(table1,table2,by='product_category_name')

print(head(appliedRightJoin,n=10))

Output: