Sometimes, you'll have string variables that need to be dealt with in more complex ways. For instance, you might want to extract a variable based on the name of a file (which is what we will do today).
We created files such as 1_stroop.csv
. Today we will want to extract the subject ID from the filename and store it as a variable in the dataframe that is loaded. So, how can we extract the ID from the filename? The stringr
package is useful for this instance (and all kinds of situations when you need to manipulate strings).
Specifically, we will use the str_split()
function within the stringr
package to split a string at a specific place:
filename <- '1_stroop.csv'
str_split(filename, '_')
[[1]]
[1] "1" "stroop.csv"