str_extract_all: return all patterns found in string concatenated as vector

笑着哭i 提交于 2020-02-24 12:08:06

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/57059625/str-extract-all-return-all-patterns-found-in-string-concatenated-as-vector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!