Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R:在向量中剪切字符串_R_Text_Vector - Fatal编程技术网

R:在向量中剪切字符串

R:在向量中剪切字符串,r,text,vector,R,Text,Vector,设x为向量 [1] "hi" "hello" "Nyarlathotep" 有没有可能从xs.t.产生一个向量,比如说y,它的成分是 [1] "hi" "hello" "Nyarl" ? 换句话说,我需要在R中使用一个命令,将文本字符串剪切到给定的长度(在上面的例子中,长度=5) 非常感谢 使用子字符串参见?子字符串 > x <- c("hi", "hello", "Nyarlathotep") >

x
为向量

[1] "hi"            "hello"         "Nyarlathotep"
有没有可能从
x
s.t.产生一个向量,比如说
y
,它的成分是

[1] "hi"            "hello"         "Nyarl"
?

换句话说,我需要在R中使用一个命令,将文本字符串剪切到给定的长度(在上面的例子中,长度=5)


非常感谢

使用
子字符串
参见
?子字符串

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

对我来说,比
子字符串
更明显的是
strtrim

> x <- c("hi", "hello", "Nyarlathotep")
> x
[1] "hi"           "hello"        "Nyarlathotep"
> strtrim(x, 5)
[1] "hi"    "hello" "Nyarl"
一个(可能)更快的选择是
sprintf()

+1或
substr(x,start=1,stop=5)
如果您想保存键入的3个字符!:-)
> x <- c("hi", "hello", "Nyarlathotep")
> x
[1] "hi"           "hello"        "Nyarlathotep"
> strtrim(x, 5)
[1] "hi"    "hello" "Nyarl"
> strtrim(x, c(1, 2, 3))
[1] "h"   "he"  "Nya"
sprintf("%.*s", 5, x)
[1] "hi"    "hello" "Nyarl"