Here are two ways to split the data frame column into multiple columns in R:
- Using tidyr::separate()
- Using stringr::str_split_fixed()
Method 1: Using tidyr::separate()
Syntax
separate(df, col)
Parameters
- df: It determines the input data frame column.
- col: It determines the final columns that it has to be separated.
Install and load “dplyr” package
install.packages("tidyr")
library(tidyr)
Visual representation
Example
library(tidyverse)
# Create sample data
df <- data.frame(
id = 1:4,
combined_values = c("A-1", "B-2", "C-3", "D-4")
)
# Print the original data
print(df)
# Split the 'combined_values' column into two columns 'letter' and 'number'
split_df <- data %>%
separate(combined_values, into = c("letter", "number"), sep = "-")
# Print the updated data
print(split_df)
Output
The number of “into” columns in separate() should match the number of elements you expect to split.
Method 2: Using stringr::str_split_fixed()
Syntax
str_split_fixed(sample_string, separator_pattern, n)
Parameters
- sample_string: It determines the input character vector.
- separator_pattern: It determines the pattern to split up by, as defined by a POSIX regular expression.
- n: It determines the number of parts the string has to be divided into.
Install and load “stringr” package
install.packages("stringr")
library(stringr)
Visual representation
Example
library(stringr)
# Create sample data
df <- data.frame(
id = 1:4,
combined_values = c("A-1", "B-2", "C-3", "D-4")
)
# Print the original data
df
df[c("letter", "number")] <- str_split_fixed(df$combined_values, "-", 2)
df_split <- df[c("id", "letter", "number")]
df_split
Output
That’s it!
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.