How to Split a String in R

04.22.2021

String operations are one of the most common tasks in programming. Splitting a string is a task used when sending and parsing data, like a csv. In this article, we will learn how to split a string in R.

To split a string, we can use the strsplit method. It has the following signature: strsplit(string, delimiter).

ad.data = "twitter,100,10000"
res = strsplit(ad.data, ",")

res

# [[1]]
# [1] "twitter" "100"     "10000"  

Notice, that the strsplit method returns a list rather than a vector. This is because the method handles some complex splitting operations. In the example above, we would have to access the value by select the first list, then the element.

res[[1]][1]
# [1] "twitter"

R has great support for vectors, and that applies to this method as well. If we have a vector of strings we would like to split, we can pass that vector to the strsplit method.

ad.data = c(
  "twitter,100,10000",
  "google,100,10000",
  "facebook,100,10000"
)
res = strsplit(ad.data, ",")

res

# [[1]]
# [1] "twitter" "100"     "10000"  
# 
# [[2]]
# [1] "google" "100"    "10000" 
# 
# [[3]]
# [1] "facebook" "100"      "10000" 

Now, we have 3 lists, each with the data from our vector.