How to Combine Two Columns into One in R dataframe?
In this article, we will discuss how to combine two columns into one in dataframe in R Programming Language.
Method 1 : Using paste() function
This function is used to join the two columns in the dataframe with a separator.
Syntax:
paste(data$column1, data$column2, sep=" ")
where
- data is the input dataframe
- column1 is the first column
- column2 to is the second column
- sep is the separator to be separated between two columns
Example 1:
R
# create dataframedata = data.frame(firstname=c("akash", "kyathi", "preethi"), lastname=c("deep", "lakshmi", "savithri"), marks=c(89, 96, 89))# displayprint(data)# combine first name and last name columns# with blank separatordata$fullname = paste(data$firstname, data$lastname, sep=" ")# displaydata |
Output:
Example 2:
R
# create dataframedata = data.frame(firstname=c("akash", "kyathi", "preethi"), lastname=c("deep", "lakshmi", "savithri"), marks=c(89, 96, 89))# displayprint(data)# combine first name and last name columns# with blank separatordata$fullname = paste(data$firstname, data$lastname, sep="--")# displaydata |
Output:
Method 2: Using unite() function
This function is available in tidyr package and we have to load that package and will combine columns.
Syntax:
unite(dataframe, combined_columnname, c(columns))
where,
- dataframe is the input dataframe
- columns are the dataframe columns to be combines
- combined_columnname is the name of the combined column
Example:
R
# import tidyr packagelibrary(tidyr)# create dataframedata = data.frame(firstname=c("akash", "kyathi", "preethi"), lastname=c("deep", "lakshmi", "savithri"), marks=c(89, 96, 89))# displayprint(data)# combine first name and last name columns# with blank separatordata = unite(data, fullname, c(firstname, lastname))# displaydata |
Output:


