让我x
成为矢量
[1] "hi" "hello" "Nyarlathotep"
Run Code Online (Sandbox Code Playgroud)
是否有可能产生一种载体,让我们说y
,从x
ST部件均
[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)
使用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)