这必须与此处描述的相似
https://github.com/tidyverse/purrr/issues/179
但是我把头撞在墙上。
考虑摘要
library(tidyverse)
library(stringr)
library(stringi)
remove_short_words <- function(x, n){
mypattern <- paste("\\w{", n, ",}", sep="")
x2 <- paste(str_extract_all(x, mypattern)[[1]], collapse=' ')
}
shopping_list <- c("apples x4", "bag of flour", "bag of sugar", "milk x2")
dd<-map2(shopping_list, 4, function(x,y) remove_short_words(x,y))
ff<-map2_df(shopping_list, 4, function(x,y) remove_short_words(x,y))
map2就像一个超级按钮,但是map2_df引发错误
Error: Argument 1 must have names
关于如何解决此问题的任何想法?谢谢!
#我添加对我有用的东西。我使用插入地图的辅助功能
remove_short_words_aux <- function(x, n){
mypattern <- paste("\\w{", n, ",}", sep="")
x2 <- paste(str_extract_all(x, mypattern)[[1]], collapse=' ')
}
remove_short_words <- function(x,n){
res<-map(x, function(x) remove_short_words_aux(x,n)) %>%
unlist %>%
tibble::enframe(name = NULL)
}
> nn<-remove_short_words(shopping_list,5)
> nn
# A tibble: 4 x 1
value
<chr>
1 "apples"
2 "flour"
3 "sugar"
4 ""
我不完全理解您要做什么,但是如果您的shopping_list
被命名,此错误就会消失:
shopping_list2 <- shopping_list %>%
set_names(., shopping_list)
map2_df(shopping_list2, 4, function(x,y) remove_short_words(x,y))
请注意,如果map2
为常数,则不需要n
和其他匿名函数定义。另外,使用map_dfr
或map_dfc
(或map2_dfr
或map2_dfc
)指定是按行还是按列合并数据。
map_dfr(shopping_list2, remove_short_words, n = 4)