OneBite.Dev - Coding blog in a bite size

cut a string in R

Code snippet on how to cut a string in R

  str <- "Hello programming world!"
  str_split <- strsplit(str, " ")
  cut_str <- str_split[[1]][1]

This code can be used to cut a string in R. The first line creates a string variable named “str” with the value “Hello programming world!“. In the second line, we use the strsplit() function to split the string on the basis of space and store it in the “strsplit” variable. The third line stores the first element of the strsplit variable which contains the first word of the string in the “cut_str” variable. Hence, the final output is the first word of the string, which is “Hello”.

r