¿Cómo podemos extraer los números enteros de las listas / objetos devueltos por sus primeras 3 soluciones?
3pitt
Úselo en regexprlugar de gregexprpara obtener los números enteros fácilmente. O utilícelo unlisten la salida como se indica en otra respuesta a continuación.
.indexOf()o algo?Respuestas:
Puedes usar
gregexprgregexpr(pattern ='2',"the2quickbrownfoxeswere2tired") [[1]] [1] 4 24 attr(,"match.length") [1] 1 1 attr(,"useBytes") [1] TRUEo quizás
str_locate_alldel paquetestringrque es un contenedor para (a partir de la versión 1.0)gregexprstringi::stri_locate_allstringrlibrary(stringr) str_locate_all(pattern ='2', "the2quickbrownfoxeswere2tired") [[1]] start end [1,] 4 4 [2,] 24 24tenga en cuenta que simplemente podría usar
stringilibrary(stringi) stri_locate_all(pattern = '2', "the2quickbrownfoxeswere2tired", fixed = TRUE)Otra opción en base
Rsería algo comolapply(strsplit(x, ''), function(x) which(x == '2'))debería funcionar (dado un vector de caracteres
x)fuente
regexprlugar degregexprpara obtener los números enteros fácilmente. O utilícelounlisten la salida como se indica en otra respuesta a continuación.Aquí hay otra alternativa sencilla.
> which(strsplit(string, "")[[1]]=="2") [1] 4 24fuente
[[1]]hace?Puede hacer que la salida sea solo 4 y 24 usando unlist:
unlist(gregexpr(pattern ='2',"the2quickbrownfoxeswere2tired")) [1] 4 24fuente
encuentra la posición de la enésima aparición de str2 en str1 (mismo orden de parámetros que Oracle SQL INSTR), devuelve 0 si no se encuentra
instr <- function(str1,str2,startpos=1,n=1){ aa=unlist(strsplit(substring(str1,startpos),str2)) if(length(aa) < n+1 ) return(0); return(sum(nchar(aa[1:n])) + startpos+(n-1)*nchar(str2) ) } instr('xxabcdefabdddfabx','ab') [1] 3 instr('xxabcdefabdddfabx','ab',1,3) [1] 15 instr('xxabcdefabdddfabx','xx',2,1) [1] 0fuente
Para encontrar solo las primeras ubicaciones, use
lapply()conmin():my_string <- c("test1", "test1test1", "test1test1test1") unlist(lapply(gregexpr(pattern = '1', my_string), min)) #> [1] 5 5 5 # or the readable tidyverse form my_string %>% gregexpr(pattern = '1') %>% lapply(min) %>% unlist() #> [1] 5 5 5Para encontrar solo las últimas ubicaciones, utilice
lapply()conmax():unlist(lapply(gregexpr(pattern = '1', my_string), max)) #> [1] 5 10 15 # or the readable tidyverse form my_string %>% gregexpr(pattern = '1') %>% lapply(max) %>% unlist() #> [1] 5 10 15fuente
También podrías usar
grep:grep('2', strsplit(string, '')[[1]]) #4 24fuente