使用R进行过滤和汇总的功能

问题描述 投票:0回答:2

我有这两张桌子;

   <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表的函数...如何创建函数?

r filter group-by dplyr summarize
2个回答
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)

1
投票

我想这解决了你的问题:

 lapply(B$b1,function(x)A%>%filter(str_detect(a1, x)) %>% group_by(a2) %>% summarize(n()))
© www.soinside.com 2019 - 2024. All rights reserved.