【发布时间】:2013-09-09 00:31:45
【问题描述】:
设x 为向量
[1] "hi" "hello" "Nyarlathotep"
是否有可能从x s.t. 生成一个向量,比如说y。它的组件是
[1] "hi" "hello" "Nyarl"
?
换句话说,我需要 R 中的一个命令,它将文本字符串切割成给定的长度(在上面,长度 = 5)。
非常感谢!
【问题讨论】:
设x 为向量
[1] "hi" "hello" "Nyarlathotep"
是否有可能从x s.t. 生成一个向量,比如说y。它的组件是
[1] "hi" "hello" "Nyarl"
?
换句话说,我需要 R 中的一个命令,它将文本字符串切割成给定的长度(在上面,长度 = 5)。
非常感谢!
【问题讨论】:
一个(可能)更快的替代方案是sprintf():
sprintf("%.*s", 5, x)
[1] "hi" "hello" "Nyarl"
【讨论】:
使用substring 详见?substring
> x <- c("hi", "hello", "Nyarlathotep")
> substring(x, first=1, last=5)
[1] "hi" "hello" "Nyarl"
上次更新
您还可以将sub 与正则表达式一起使用
> sub("(.{5}).*", "\\1", x)
[1] "hi" "hello" "Nyarl"
【讨论】:
substr( x , start = 1 , stop = 5 ),如果您想保存这 3 个打字字符! :-)
对我来说比substring 更明显的是strtrim:
> x <- c("hi", "hello", "Nyarlathotep")
> x
[1] "hi" "hello" "Nyarlathotep"
> strtrim(x, 5)
[1] "hi" "hello" "Nyarl"
substring 非常适合从给定位置的字符串中提取数据,但 strtrim 完全符合您的要求。
第二个参数是widths,它可以是一个宽度与输入向量长度相同的向量,在这种情况下,每个元素都可以修剪指定的数量。
> strtrim(x, c(1, 2, 3))
[1] "h" "he" "Nya"
【讨论】: