Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
str_extract_all:返回串接为向量的字符串中找到的所有模式_R_Dplyr_Stringr - Fatal编程技术网

str_extract_all:返回串接为向量的字符串中找到的所有模式

str_extract_all:返回串接为向量的字符串中找到的所有模式,r,dplyr,stringr,R,Dplyr,Stringr,我想提取除模式之外的所有内容,并以字符串形式返回这个concetenated 我试着把Stru_和Sappy以及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 st

我想提取除模式之外的所有内容,并以字符串形式返回这个concetenated

我试着把Stru_和Sappy以及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=""))
x=c(“a_1”、“a_20”、“a_40”、“a_30”、“a_28”)
数据%
突变(年龄新=str提取(年龄,“[^a]”)
#把str\u extract\u all和sapply结合起来是行不通的
数据%>%
突变(年龄=sapply(str_extract_all(x,“[^a]”),函数(x)cat(x,sep=“”))
类(str\u extract\u all(x,“[^a]”)
sapply(str_extract_all(x,“[^a]”),function(x)cat(x,sep=”“)

返回NULL而不是串联模式

而不是
cat
,我们可以使用
粘贴
。此外,使用
tidyverse
,可以使用
map
stru c
(代替
paste
-来自
stringr


使用'OP'代码

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

如果目的是获取数字

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

这里是一个非tidyverse解决方案,仅使用stringr

apply(str_extract_all(column,regex_command,simplify = TRUE),1,paste,collapse="")
“simplify”=TRUE changed str_extract_all以输出矩阵,并在矩阵上应用迭代。我是从你那里得到这个主意的

示例:提取行名(mtcar)中的所有“r”,并将其连接为向量

library(stringr)
apply(str_extract_all(rownames(mtcars),"r",simplify = TRUE),1,paste,collapse="")

您还可以避免在第一个解决方案中使用
map\u chr
,并使用:
str\u extract\u all(x,“[^a+”,simplify=T)[,1]
tidyverse答案似乎比apply解决方案更好,因为它在连接时不会将空结果视为结果。如果您共享一段数据,我们可以以更有效的方式帮助您。
library(stringr)
apply(str_extract_all(rownames(mtcars),"r",simplify = TRUE),1,paste,collapse="")