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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15897236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:52:26  来源:igfitidea点击:

Extract the first (or last) n characters of a string

stringr

提问by Lisa Ann

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

我想提取字符串的第一个(或最后一个)n 个字符。这将等同于 ExcelLEFT()RIGHT(). 一个小例子:

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

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

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

b
# [1] "left"

What should I do?

我该怎么办?

回答by rcs

See ?substr

?substr

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

回答by juba

The stringrpackage provides the str_subfunction, which is a bit easier to use than substr, especially if you want to extract right portions of your string :

stringr包提供了str_sub比 更易于使用的函数,substr特别是如果您想提取字符串的正确部分:

R> str_sub("leftright",1,4)
[1] "left"
R> str_sub("leftright",-5,-1)
[1] "right"

回答by Andrea Cirillo

You can easily obtain Right() and Left() functions starting from the Rbase package:

您可以从 Rbase 包中轻松获取 Right() 和 Left() 函数:

  • right function

    right = function (string, char) {
        substr(string,nchar(string)-(char-1),nchar(string))
    }
    
  • left function

    left = function (string,char) {
        substr(string,1,char)
    }
    
  • 正确的功能

    right = function (string, char) {
        substr(string,nchar(string)-(char-1),nchar(string))
    }
    
  • 左函数

    left = function (string,char) {
        substr(string,1,char)
    }
    

you can use those two custom-functions exactly as left() and right() in excel. Hope you will find it useful

您可以完全按照 Excel 中的 left() 和 right() 使用这两个自定义函数。希望你会觉得它有用

回答by Marcos RF

Make it simple and use R basic functions:

让它变得简单并使用 R 基本函数:

# To get the LEFT part:
> substr(a, 1, 4)
[1] "left"
> 
# To get the MIDDLE part:
> substr(a, 3, 7)
[1] "ftrig"
> 
# To get the RIGHT part:
> substr(a, 5, 10)
[1] "right"

The substr()function tells you where start and stop substr(x, start, stop)

substr()功能告诉您开始和停止的位置substr(x, start, stop)