In this course, we will often be dealing with text data. These are also called character strings in R.
example <- "Hello World"
To merge two strings we can use the paste() function. This function uses a separator which is by default ” “.
new_example <- paste("Hello World", "how is your day")
##[1] "Hello World how is your day"
We can also change that separator.
new_example <- paste("Hello World", "how is your day", sep=", ")
new_example
##[1] "Hello World, how is your day"
To split a string we can use the strsplit() function.
strsplit(new_example, ",")
##[1] "Hello World" " how is your day"
When using the strsplit()function, R returns us a nested list. To access only the elements of the sublist we can ask for the first element in the sublist [[1]].
strsplit(new_example, ",")[[1]]
## [1] "Hello World" " how is your day"
As you will see in the remainder of the course, some functions return nested lists. This is a frequent source of trouble for people who are new to R. So if you have difficulties accessing specific elements in a vector, check to see whether you are dealing with a sublist.
access_time Last update May 8, 2020.