0

我有这两张桌子;

   <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 表......我如何制作这个函数?

4

2 回答 2

1

我想这解决了你的问题:

 lapply(B$b1,function(x)A%>%filter(str_detect(a1, x)) %>% group_by(a2) %>% summarize(n()))
于 2017-12-29T02:14:55.940 回答
1

这里我设计了一个名为 的函数count_fun,它有四个参数。dat是一个数据框AScol是一个带有字符串的列,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_funusinglapply来遍历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)
于 2017-12-29T02:17:24.833 回答