str_extract_all:返回在字符串中找到的所有模式连接为向量 [英] str_extract_all: return all patterns found in string concatenated as vector

查看:17
本文介绍了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

推荐答案

我们可以使用paste代替cat.此外,通过 tidyverse,可以使用 mapstr_c(代替 paste - 来自 字符串)

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

<小时>

如果目的是获取数字


If the intention is to get the numbers

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

这篇关于str_extract_all:返回在字符串中找到的所有模式连接为向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆