How to use stringr package In R Language
The stringr package in R is used to carry out string manipulations. It helps us perform modifications related to string. The package can be download and installed into the working space using the following command :
install.packages("stringr")
The str_split_fixed method in stringr package is used to split up a string into a fixed number of pieces. The method transforms strings into the specified number of substrings. The specified pattern should be of unit length.
Syntax:
str_split_fixed(str, pattern , n
Parameter :
- str: The string vector to be split.
- pattern: Pattern to split up the string by.
- n: The number of pieces to split the string into.
Example: Split dataframe variable into multiple columns
R
library ( "stringr" ) # creating a dataframe data_frame <- data.frame ( col1 = c ( "val_1" , "val_2" , "val_3" , "val_4" ) ) print ( "Original DataFrame" ) print (data_frame) # splitting values in column print ( "Modified DataFrame" ) str_split_fixed (data_frame$col1, "_" , 2) |
Output:
[1] "Original DataFrame" col1 1 val_1 2 val_2 3 val_3 4 val_4 [1] "Modified DataFrame" [,1] [,2] [1,] "val" "1" [2,] "val" "2" [3,] "val" "3" [4,] "val" "4"
Split DataFrame Variable into Multiple Columns in R
In this article, we will discuss how to split dataframe variables into multiple columns using R programming language.