Concatenate two columns of dataframe in R

To Concatenate two columns of dataframe in R we generally use paste() Function . Let’s see how to

  • Concatenate two columns of dataframe in R.

Let’s first create the dataframe.

### Create Data Frame

df1 = data.frame(State = c('Arizona','Georgia','Newyork','Indiana','Florida'), 
                 State_code = c('AZ','GG','NY','IN','FL'), 
                 Score=c(62,47,55,74,31))
df1

So the resultant dataframe will be

Concatenate two columns of dataframe in R 1

 

Concatenate two string columns:

Let’s concatenate two columns of dataframe with paste function as shown below

### Concatenate two string columns

df1$state_and_code = paste(df1$State,df1$State_code)
df1

So the result will be

Concatenate two columns of dataframe in R 2

 

Concatenate two columns with space in R:

Let’s concatenate two columns of dataframe with + as shown below

### Concatenate two string columns with "+"

df1$state_and_code = paste(df1$State,"+",df1$State_code)
df1

So the result will be

Concatenate two columns of dataframe in R 3

 

Concatenate two columns with – (hyphen) in R:

Let’s concatenate two columns of dataframe with – (hyphen) as shown below

### Concatenate two string columns with hypen

df1$state_and_code = paste(df1$State,"-",df1$State_code)
df1

So the result will be

Concatenate two columns of dataframe in R 4

 

Concatenate two columns of dataframe in R - image previous-small-11-1 on http://www.datasciencemadesimple.com                                                                                                                Concatenate two columns of dataframe in R - image next_small-11-1 on http://www.datasciencemadesimple.com