R:剪切向量中的字符串

Avi*_*tus 7 text r vector

让我x成为矢量

[1] "hi"            "hello"         "Nyarlathotep"
Run Code Online (Sandbox Code Playgroud)

是否有可能产生一种载体,让我们说y,从xST部件均

[1] "hi"            "hello"         "Nyarl"
Run Code Online (Sandbox Code Playgroud)

换句话说,我需要一个R中的命令,它将文本字符串切割为给定的长度(在上面,长度= 5).

非常感谢!

A5C*_*2T1 10

substring我更明显的是strtrim:

> x <- c("hi", "hello", "Nyarlathotep")
> x
[1] "hi"           "hello"        "Nyarlathotep"
> strtrim(x, 5)
[1] "hi"    "hello" "Nyarl"
Run Code Online (Sandbox Code Playgroud)

substring非常适合从给定位置的字符串中提取数据,但strtrim确实可以满足您的需求.

第二个参数是widths,它可以是宽度与输入向量长度相同的向量,在这种情况下,每个元素可以按指定的量进行修剪.

> strtrim(x, c(1, 2, 3))
[1] "h"   "he"  "Nya"
Run Code Online (Sandbox Code Playgroud)


Jil*_*ina 6

使用substring查看详细信息?substring

> x <- c("hi", "hello", "Nyarlathotep")
> substring(x, first=1, last=5)
[1] "hi"    "hello" "Nyarl"
Run Code Online (Sandbox Code Playgroud)

上次更新 您也可以使用sub正则表达式

> sub("(.{5}).*", "\\1", x)
[1] "hi"    "hello" "Nyarl"
Run Code Online (Sandbox Code Playgroud)

  • +1或`substr(x,start = 1,stop = 5)`如果你想保存那3个字符的输入!:-) (3认同)