How to use separate() function of dplyr package library In R Language
To split a column into multiple columns in the R Language, we use the separator() function of the dplyr package library. The separate() function separates a character column into multiple columns with a regular expression or numeric locations. The function takes input character vector as an argument and the output column names in a vector as an argument and returns final data vector.
Syntax:
separate( sample_data, col )
Parameter:
- sample_data: determines the input data frame column.
- col: determines the final columns that it has to be separated.
Example: Split column into multiple columns
R
# create sample data frame df <- data.frame (Name= c ( 'Priyank Mishra' , 'Abhiraj Srivastava' , 'Pawananjani Kumar' ), State= c ( "Uttar Pradesh" , "Maharashtra" , "Bihar" )) print ( " Data frame before splitting: " ) df # load dplyr and tidyr library library (dplyr) library (tidyr) # Split name column into firstname and last name df <- df %>% separate (Name, c ( 'First Name' , 'Last Name' )) print ( " Data frame after splitting: " ) df |
Output:
Data frame before splitting: Name State 1 Priyank Mishra Uttar Pradesh 2 Abhiraj Srivastava Maharashtra 3 Pawananjani Kumar Bihar Data frame after splitting: First Name Last Name State 1 Priyank Mishra Uttar Pradesh 2 Abhiraj Srivastava Maharashtra 3 Pawananjani Kumar Bihar
How to Split Column Into Multiple Columns in R DataFrame?
In this article, we will discuss how to split a column from a data frame into multiple columns in the R programming Language.