Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
826 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 Reply

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...