我有一些特定格式的句子,我需要定期拆分它们 句子看起来像这样
"abxyzpqrst34245"
"mndeflmnop6346781"
我想在以下字符之后拆分这些句子:c(2,5,10),以便输出为:
[1] c("ab", "xyz", "pqrst", "34245")
[2] c("mn", "def", "lmnop", "6346781")
注意:第3次分割后的数字字符具有可变长度,而前面的数字字符具有固定长度。
我尝试使用cut
,但它只适用于整数向量
我查看了split
,但我不确定它是否在没有因素的情况下起作用
所以,我最后和substr
一起分别将每个句子分开:
substr("abxyzpqrst34245", 1,2)
[1] "ab"
substr("abxyzpqrst34245", 3,5)
[1] "xyz"
substr("abxyzpqrst34245", 6,10)
[1] "pqrst"
substr("abxyzpqrst34245", 11,10000)
[1] "34245"
我正在使用这个漫长的过程来分割这些字符串。有没有更简单的方法来实现这种分裂?
答案 0 :(得分:5)
您正在寻找(经常被忽视的)substring
:
x <- "abxyzpqrst34245"
substring(x,c(1,3,6,11),c(2,5,10,nchar(x)))
[1] "ab" "xyz" "pqrst" "34245"
这很方便,因为它是完全矢量化的。如果你想依次对多个字符串执行此操作,可以执行以下操作:
x <- c("abxyzpqrst34245","mndeflmnop6346781")
> lapply(x,function(y) substring(y,first = c(1,3,6,11),last = c(2,5,10,nchar(y))))
[[1]]
[1] "ab" "xyz" "pqrst" "34245"
[[2]]
[1] "mn" "def" "lmnop" "6346781"
答案 1 :(得分:3)
如果你有一个要拆分的字符串向量,你也可能会找到read.fwf()
。像这样使用它:
x <- c("abxyzpqrst34245", "mndeflmnop6346781")
df <- read.fwf(file = textConnection(x),
widths = c(2,3,5,10000),
colClasses = "character")
df
# V1 V2 V3 V4
# 1 ab xyz pqrst 34245
# 2 mn def lmnop 6346781
str(df)
# 'data.frame': 2 obs. of 4 variables:
# $ V1: chr "ab" "mn"
# $ V2: chr "xyz" "def"
# $ V3: chr "pqrst" "lmnop"
# $ V4: chr "34245" "6346781"