Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
824 views
in Technique[技术] by (71.8m points)

r - str_extract_all: return all patterns found in string concatenated as vector

I want to extract everything but a pattern and return this concetenated in a string.

I tried to combine str_extract_all together with sapply and cat

x = c("a_1","a_20","a_40","a_30","a_28")
data <- tibble(age = x)


# extracting just the first pattern is easy
data %>% 
  mutate(age_new = str_extract(age,"[^a_]"))
# combining str_extract_all and sapply doesnt work
data %>% 
  mutate(age_new = sapply(str_extract_all(x,"[^a_]"),function(x) cat(x,sep="")))


class(str_extract_all(x,"[^a_]"))
sapply(str_extract_all(x,"[^a_]"),function(x) cat(x,sep=""))

Returns NULL instead of concatenated patterns

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Instead of cat, we can use paste. Also, with tidyverse, can make use of map and str_c (in place of paste - from stringr)

library(tidyverse)
data %>% 
  mutate(age_new = map_chr(str_extract_all(x, "[^a_]+"), ~ str_c(.x, collapse="")))

using `OP's code

data %>%
    mutate(age_new = sapply(str_extract_all(x,"[^a_]"),
               function(x) paste(x,collapse="")))

If the intention is to get the numbers

library(readr)
data %>%
     mutate(age_new = parse_number(x))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...