left: Leftmost n characters of a string.

Description Usage Arguments Value Reuse good code Alternative

Description

A standard left function.

Usage

1
left(s, n)

Arguments

s

Character vector.

n

Scalar of vector of the same lenght as s. If n < 0, returns all except the rightmost n. If n == 0, returns an empty string.

Value

The leftmost n characters of a string.

Reuse good code

"The single biggest way to improve both the quality of your code and your productivity is to reuse good code (...) Many algorithms have already been invented, tested, discussed in the trade literature, reviewed, and improved".

–Code complete 2, by Steve McConnell.

Alternative

A more powerful and general alternative is stringr::str_sub():

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
library(stringr)
library(ctfs)
string <- c("abcdefg", "abcdefg", "abcdefg")
# You can do the same
stringr::str_sub(string, end = 2)
#> [1] "ab" "ab" "ab"
left(string, n = 2)
#> [1] "ab" "ab" "ab"

# But you can also do more
stringr::str_sub(string, start= 2, end = 4)
#> [1] "bcd" "bcd" "bcd"

forestgeo/ctfs documentation built on May 3, 2019, 6:44 p.m.