Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/69.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_String - Fatal编程技术网

R 在最接近某个字符号的完整单词处剪切字符串

R 在最接近某个字符号的完整单词处剪切字符串,r,string,R,String,我试图根据以下标准将字符串向量分成两部分(我只想保留第一位): 它应该在一个完整单词后拆分(即空格出现的位置) 它应该在最靠近第12个字符的空格处剪切 例如: textvec <- c("this is an example", "I hope someone can help me", "Thank you in advance") 到目前为止,我尝试的是: 我能够得到出现在第12个字符之前或第12个字符处的完整单词,如下所示: "this is an" , "I hope som

我试图根据以下标准将字符串向量分成两部分(我只想保留第一位):

  • 它应该在一个完整单词后拆分(即空格出现的位置)
  • 它应该在最靠近第12个字符的空格处剪切
例如:

textvec <- c("this is an example", "I hope someone can help me", "Thank you in advance")
到目前为止,我尝试的是: 我能够得到出现在第12个字符之前或第12个字符处的完整单词,如下所示:

"this is an" , "I hope someone", "Thank you in"
t13 <- substr(textvec , 1, 13) #gives me first 13 characters of each string
lastspace <- lapply(gregexpr(" ", t13), FUN=function(x) x[length(x)]) #gives me last space before/at 13th character
result <- substr(t13, start=1, stop=lastspace)

t13我们可以使用
gregexpr
在12处找到最近的空格,然后使用
substr
剪切字符串

substr(textvec, 1, sapply(gregexpr("\\s+", textvec), 
            function(x) x[which.min(abs(12 - x))])-1)
#[1] "this is an"     "I hope someone" "Thank you in"  

使用
cumsum

sapply(strsplit(textvec, ' '), function(i) paste(i[cumsum(nchar(i)) <= 12], collapse = ' '))

#[1] "this is an"     "I hope someone" "Thank you in"

sapply(strsplit(textvec.)),function(i)paste(i[cumsum(nchar(i))谢谢!虽然Akrun的答案对我给出的示例也有效,但我接受这个答案,因为如果字符串短于12,它还包括最后一个单词。这非常简洁!我的答案太相似了:
lappy(textvec,function(x)substr(x,1,unlist(gregexpr(“,x))[which.min(abs(12-unlist(gregexpr(“,x))))]-1]