我有这两张桌子;
<A> <B>
a1 a2 b1
ABC CAFE AB
ABD DRINK BF
ABF CAFE ..
ABFF DRINK
.. ..
我想知道表A中包含B到a1的汇总表,就像这样;
library(dplyr)
library(stringr)
A1 <- A %>%
filter(str_detect(a1, "AB")) %>%
group_by(a2) %>%
summarize(n())
A2 <- A %>%
filter(str_detect(a1, "BF")) %>%
group_by(a2) %>%
summarize(n())
但是,我应该多次编写代码,以便我想在str_detect函数中输入B表的函数...如何创建函数?
答案 0 :(得分:1)
我想这解决了你的问题:
lapply(B$b1,function(x)A%>%filter(str_detect(a1, x)) %>% group_by(a2) %>% summarize(n()))
答案 1 :(得分:1)
在这里,我设计了一个名为count_fun
的函数,它有四个参数。 dat
是A
之类的数据框,Scol
是包含字符串的列,Gcol
是分组列,String
是测试字符串。请参阅https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html了解如何使用dplyr
设计功能。
library(dplyr)
library(stringr)
count_fun <- function(dat, Scol, Gcol, String){
Scol <- enquo(Scol)
Gcol <- enquo(Gcol)
dat2 <- dat %>%
filter(str_detect(!!Scol, String)) %>%
group_by(!!Gcol) %>%
summarize(n())
return(dat2)
}
count_fun(A, a1, a2, "AB")
# # A tibble: 2 x 2
# a2 `n()`
# <chr> <int>
# 1 CAFE 2
# 2 DRINK 2
count_fun(A, a1, a2, "BF")
# # A tibble: 2 x 2
# a2 `n()`
# <chr> <int>
# 1 CAFE 1
# 2 DRINK 1
然后,我们可以count_fun
使用lapply
来循环遍历B
中的每个元素。
lapply(B$b1, function(x){
count_fun(A, a1, a2, x)
})
# [[1]]
# # A tibble: 2 x 2
# a2 `n()`
# <chr> <int>
# 1 CAFE 2
# 2 DRINK 2
#
# [[2]]
# # A tibble: 2 x 2
# a2 `n()`
# <chr> <int>
# 1 CAFE 1
# 2 DRINK 1
数据强>
A <- read.table(text = "a1 a2
ABC CAFE
ABD DRINK
ABF CAFE
ABFF DRINK
",
header = TRUE, stringsAsFactors = FALSE)
B <- data.frame(b1 = c("AB", "BF"), stringsAsFactors = FALSE)