提取字符串的前(或最后)n 个字符

提取字符串的前(或最后)n 个字符

问题描述:

我想提取字符串的第一个(或最后一个)n 个字符.这相当于 Excel 的 LEFT()RIGHT().一个小例子:

I want to extract the first (or last) n characters of a string. This would be the equivalent to Excel's LEFT() and RIGHT(). A small example:

# create a string
a <- paste('left', 'right', sep = '')
a
# [1] "leftright"

我想生成b,一个等于a的前4个字母的字符串:

I would like to produce b, a string which is equal to the first 4 letters of a:

b
# [1] "left"

我该怎么办?

查看 ?substr

R> substr(a, 1, 4)
[1] "left"