str_extract_all:返回在字符串中找到的所有组合为向量的模式 [英] str_extract_all: return all patterns found in string concatenated as vector
本文介绍了str_extract_all:返回在字符串中找到的所有组合为向量的模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想提取除模式以外的所有内容,并将其转化为字符串。
I want to extract everything but a pattern and return this concetenated in a string.
我试图将str_extract_all与sapply和cat结合在一起
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=""))
返回NULL代替串联模式
Returns NULL instead of concatenated patterns
推荐答案
代替 cat
,我们可以使用粘贴
。另外,使用 tidyverse
,可以使用 map
和 str_c
(代替粘贴
-来自 stringr
)
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="")))
使用OP的代码
using `OP's code
data %>%
mutate(age_new = sapply(str_extract_all(x,"[^a_]"),
function(x) paste(x,collapse="")))
< hr>
如果打算获取数字
If the intention is to get the numbers
library(readr)
data %>%
mutate(age_new = parse_number(x))
这篇关于str_extract_all:返回在字符串中找到的所有组合为向量的模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文