Creating and Subsetting Text StringsRyan NagelkirkOctober 27, 2015It is often very helpful to be able to create and manipulate text strings. Here, we will create a few strings and then subset them to create a new string that will be the name of a file that we’ll then load. The functions used are substring substr() and paste paste(). These functions can also be used to subset data via row or column names, or to go through a list of files and load only those that contain a certain string. It is most useful when doing loops with file, column, or row names that follow a similar naming system. First, we’ll create a csv to load later. This will save to your current working directory. We’ll delete it afterward.
Now create two variables to represent two different text strings.
I could have done that second line differently. Using the paste and substring functions, we could use some of the text from the first variable. Substr() will get us only the text we want, in this case the text between (and including) the 5th and 9th letters: “_data"
So let’s put that together using paste()
Now let’s use the text strings to create a file name that we want to load. In this case, we’ll make the name “test_csv” because it is the name of the file we created earlier.
Now that we have the name, load the data using the read.csv() function.
We’ve now created a file name and loaded it using portions of other names. This is a fundamental part of writing code that now, by combining different portions of strings, can navigate through directories, create new names for files, and select subsets of files within a directory. There are many other uses and it can make a code more powerful and adaptable. This will delete the file from you directory.
0 Comments
Working with text in RAnonymous AntelopeOctober 26, 2015Using substr() allows you to extract/replace items in a character vector. It is similar to several functions available in excel. It can also be useful when working with date/time information (i.e., pull out month, day, or year).
Use gsub to search and replace elements within a character vector.
Change to uppercase or lowercase
|
Spatial Ecology @ MSUClick on "Category" below to search for R code compiled by the Zarnetske Spatial & Community Ecology Lab and students in MSU's Spatial Ecology graduate course (FOR870/FW870) Category
All
Archive
October 2016
|