Basic String Operations in R

Basic String Operations in R

1. nchar() is used to find length of a string

Code:

nchar(“Introduction to R”)

Output:

[1] 17

2. length() returns number of elements in object. So for single string it will return 1

Code:

length(“Introduction to R”)

Output:

[1] 1

3. paste() is used to concatenate strings. By default, paste() inserts a single space between pairs of strings.

Code:

paste(“Introduction”, “to”,” R”)

Output:

[1] Introduction to R

The default setting can be overridden using sep argument in paste()

Code:

paste(“Introduction”, “to”,” R”,”sep = “:”)

Output:

[1] Introduction:to:R

4. replicate() or rep() helps duplicate same string multiple times

Code:

replicate(3, “Introduction to R”)

rep(“Introduction to R”, 3)

Output:

[1] “Introduction to R” “Introduction to R” “Introduction to R”

[1] “Introduction to R” “Introduction to R” “Introduction to R”


Leave a Reply