字符向量的每个项目中的最后一个空格的索引

问题描述 投票:0回答:6

我有一个角色矢量x作为

 [1] "Mt. Everest" "Cho oyu" "Mont Blanc" "Ojos del Salado"

我正在寻找一个输出给我最后一个空白的索引

[1] 4 4 5 9

我相信我需要使用sapply,以便我的函数适用于向量中的每个项目,但无法写入:

sapply(x,myFunction)

对于myFunction,我写了类似的东西:

myFunction <- function(a){
match(a,c(" "))
}

这可以理解地给所有NA,因为没有项目只是一个空间。

我不想为此使用stringr

r vector sapply
6个回答
1
投票

regexpr会做......

v <- c("Mt. Everest", "Cho oyu", "Mont Blanc", "Ojos del Salado")

#find position of space, not followed by a space until the end of string    
regexpr(" [^ ]*$", v)

#int [1:4] 4 4 5 9

要么

library(dplyr)
data.frame( v = v ) %>% mutate( lastspace = regexpr(" [^ ]*$", v) )

#                 v lastspace
# 1     Mt. Everest         4
# 2         Cho oyu         4
# 3      Mont Blanc         5
# 4 Ojos del Salado         9

1
投票

你可以使用gregexpr实现这一目标

x = c("Mt. Everest", "Cho oyu", "Mont Blanc", "Ojos del Salado")

lapply(gregexpr(pattern=" ", x), max)

如果您希望将答案作为矢量

> sapply(gregexpr(pattern=" ", x), max)
[1] 4 4 5 9

信用:在@markus的帮助下,答案得到了改善


1
投票

使用mapply的一种方法是在空格上分割字符,计算最后一个元素的字符数,并从字符串的总字符中减去它。

myFunction <- function(a){
  mapply(function(p, q) q - nchar(p[length(p)]), strsplit(a, "\\s+"), nchar(a))
}  

myFunction(x)
#[1] 4 4 5 9

这个怎么运作 :

让我们从列表中取出最后一个元素:

x <- "Ojos del Salado"

#Split on whitespace
p = strsplit(x, "\\s+")[[1]]
p
#[1] "Ojos"   "del"    "Salado"

#Select the last element 
p[length(p)]
#[1] "Salado"

#Count the number of characters in the last element
nchar(p[length(p)])
#[1] 6

#Subtract it from total characters in x
nchar(x) - nchar(p[length(p)])
#[1] 9

数据

x <- c("Mt. Everest", "Cho oyu" ,"Mont Blanc", "Ojos del Salado")

0
投票

使用stringr

library(stringr)
myFunction <- function(a){
  str_locate(a, " (?=[^ ]*$)")[, 1]
}

myFunction(x)
# [1] 4 4 5 9

使用stringi(并避免正则表达式):

library(stringi)
myFunction2 <- function(a){
  stri_locate_last_fixed(a, " ")[, 1]
}

myFunction2(x)
# [1] 4 4 5 9

使用基础R的strsplit()(并避免使用正则表达式):

myFunction3 <- function(a){
  sapply(strsplit(x, ""), function(x) max(which(x == " ")))
}

myFunction3(x)
# [1] 4 4 5 9

数据:

x <- c("Mt. Everest", "Cho oyu", "Mont Blanc", "Ojos del Salado")

0
投票

你也可以尝试grepRaw()

sapply(x, function(x) max(grepRaw(" ", x, all = TRUE)))

Mt. Everest         Cho oyu      Mont Blanc Ojos del Salado 
          4               4               5               9 

使用dplyr

data.frame(x) %>%
 mutate(res = sapply(x, function(x) max(grepRaw(" ", x, all = TRUE))))

                x res
1     Mt. Everest   4
2         Cho oyu   4
3      Mont Blanc   5
4 Ojos del Salado   9

0
投票

一个简单而简洁的选择

sapply(a,function(x){last(which(strsplit(x,"")[[1]]==" "))})

    Mt. Everest         Cho oyu      Mont Blanc Ojos del Salado 
              4               4               5               9 
© www.soinside.com 2019 - 2024. All rights reserved.