You can use the following syntax to split a character string in R and get the first element:
strsplit(string_var, " ")[[1]][1]
This particular example splits a character string based on spaces, but you can provide any value you’d like to the second argument of the strsplit() function to split by a different delimiter.
For example, you could use the following syntax to split a string based on dashes:
strsplit(string_var, "-")[[1]][1]
The following example shows how to use this syntax in practice.
Example: Split Character String and Get First Element in R
The following code shows how to split a particular character string in R based on spaces and get the first element:
#define string variable
string_var <- "This is a string variable"
#split string variable based on spaces and get first element
strsplit(string_var, " ")[[1]][1]
[1] "This"
The strsplit() function returns “This”, which is the first element in the string variable.
Note that if you’d like to get a different element, you just need to change the number in the last bracket.
For example, you can use the following syntax to split the character string based on spaces and get the second element:
#define string variable
string_var <- "This is a string variable"
#split string variable based on spaces and get second element
strsplit(string_var, " ")[[1]][2]
[1] "is"
This time the strsplit() function gets the second element.
Also note that we can change the space in the strsplit() function to a different delimiter, such as a dash, to separate a string variable based on dashes and get the first element:
#define string variable
string_var <- "This-is-a-string-variable"
#split string variable based on dashes and get first element
strsplit(string_var, "-")[[1]][1]
[1] "This"
The strsplit() function correctly returns “This” as the first element.
Related: An Introduction to the strsplit() Function in R
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Remove Last Character from String in R
How to Find Location of Character in a String in R
How to Select Columns Containing a Specific String in R