Labs ICT
โญ Pro Login

Strings

Text data โ€” strings โ€” is everywhere in data analysis. Names, categories, addresses, reviews, tweets. R has a solid set of tools for working with strings, and they're surprisingly intuitive once you get the hang of them.

Creating Strings

You create a string by wrapping text in quotes. R doesn't care whether you use single or double quotes, but you need to be consistent. Double quotes are more common in R, but single quotes are fine too. Just pick one and stick with it.


# Creating strings
greeting <- "Hello, world!"
name <- 'Alice'
greeting
name
    
Try it Yourself โ†’

Single vs Double Quotes

You can embed one type of quote inside the other. For example, if your string contains an apostrophe, wrap it in double quotes. If it contains double quotes, wrap it in single quotes. If it has both, use the backslash escape: \" or \'.


# Mixing quotes
sentence <- "It's a nice day"
quote <- 'She said "hello"'
sentence
quote
    
Try it Yourself โ†’

paste() โ€” Gluing Strings Together

paste() joins multiple strings into one. You give it the pieces and it combines them with a space (by default) or a separator you choose. It's like glue for text. There's also paste0() which uses no separator at all.


# Combining strings
first <- "John"
last <- "Doe"
paste(first, last)
paste(first, last, sep = ", ")
paste0(first, last)
    
Try it Yourself โ†’

nchar() โ€” How Long Is It?

nchar() tells you the number of characters in a string. This includes letters, spaces, punctuation โ€” everything. It's useful for validation (like checking if a phone number has the right length) or text analysis.


# String length
word <- "R is fun"
nchar(word)
nchar("")
    
Try it Yourself โ†’

toupper() and tolower()

Need to standardize some text? toupper() converts everything to uppercase and tolower() converts everything to lowercase. This is incredibly handy when you're cleaning data โ€” "New York" and "new york" might be the same city, but R sees them as different strings until you normalize the case.


# Changing case
text <- "R Stats"
toupper(text)
tolower(text)
    
Try it Yourself โ†’

Strings are fun to play with because you see results immediately. There's a lot more to string manipulation in R, but these basics will carry you far. Next up: the logic that powers decision-making in R.

๐Ÿงช Quick Quiz

Which function combines strings in R?