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"