---
title: "Substrings"
author: "Statistical Computing, 36-350"
date: "Friday September 2, 2016"
---

Number of characters
===

To count how many characters in a string, don't use `length()`, use `nchar()`

```{r}
nchar("coffee")
nchar("code monkey")
length("code monkey")
length(c("coffee", "code monkey"))
```

`nchar()` vectorizes
===

Can pass a vector of strings to `nchar()`, and it returns the character counts in each element. This is called **vectorization**

```{r}
nchar(c("coffee", "code monkey"))
nchar(c("Spider-Man", "does whatever", "a spider can"))
```

Reminder: vectorization
===

Some basic examples of vectorization

```{r}
c(1,2,3) + c(1,2,3)
1:10 - 1 # This is an example of recycling
1:10 * -1 # So is this
abs(-3:3)
log(1:5)
log(exp(1:7)) # Notice two vectorizations happening here
```

Getting a substring
===

Grab a subseqence of characters from a string, called a substring, using `substr()`

```{r}
phrase = "Give me a break"
substr(phrase, 1, 4)
substr(phrase, nchar(phrase)-4, nchar(phrase))
substr(phrase, nchar(phrase)+1, nchar(phrase)+10)
```

`substr()` vectorizes
===

Just like `nchar()` (and many other functions)

```{r}
presidents = c("Clinton", "Bush", "Reagan", "Carter", "Ford")
substr(presidents, 1, 2) # Grab the first 2 letters from each
substr(presidents, 1:5, 1:5) # Grab the first, 2nd, 3rd, etc.
substr(presidents, 1, 1:5) # Grab the first, first 2, first 3, etc.
substr(presidents, nchar(presidents)-1, nchar(presidents)) # Grab the last 2 letters from each
```

Replacements
===

To replace a character, or a substring, use `substr()` 

```{r}
phrase
substr(phrase, 1, 1) = "L"
phrase # "G" changed to "L"
substr(phrase, 1000, 1001) = "R"
phrase # Nothing happened
substr(phrase, 1, 4) = "Show"
phrase # "Live" changed to "Show"
```

Vectorized replacements
===

Another example of `substr()` vectorizing

```{r}
presidents
first.letters = substr(presidents, 1, 1)
first.letters.scrambled = sample(first.letters)
substr(presidents, 1, 1) = first.letters.scrambled;
presidents
```

Some replacement quirks
===

You can only replace exact many letters as you specify

```{r}
phrase
substr(phrase, 1, 4) = "Provide"
phrase # Only replaced the first 4 letters
substr(phrase, nchar(phrase)-4, nchar(phrase)) = "cat"
phrase # Only replaced the first 3 letters, in the last word
```