【问题标题】:filter dataframe inside function在函数内过滤数据框
【发布时间】:2017-03-08 19:31:34
【问题描述】:

我看到了类似的问题,但无法应用它们来解决我的问题。我想要一个函数来过滤少于 3 个观察值的组。因为我想要几个数据帧,所以我需要一个函数。我用 dplyr 和合并完成了它,但我想要一个更好的代码,只使用 dplyr 或数据表。

data <- read.table(text="
col1       col2 
group1   some  
group1   some2     
group1   some3
group2   some  
group2   some2",header=TRUE,fill=TRUE,stringsAsFactors=FALSE)


filter3 <- function(df, colgroup1) {
  df %>%
    group_by_(colgroup1) %>%
    summarise_(Count = ~n()) #%>%
}
great3<-function(x, col){
  x[x[,col] >=3 ,]
}

allfiltered<-function(df,colgroup1){
  counts<-filter3(df,colgroup1)
  final<-great3(counts,"Count")
  merge(df,final, by=colgroup1)}

allfiltered(data,"col1")

#expected, count column dispensable, (function for 1 df or list of dfs wanted)
    col1  col2 Count
1 group1  some     3
2 group1 some2     3
3 group1 some3     3

【问题讨论】:

标签: r data.table dplyr


【解决方案1】:

您可以直接使用group_by %&gt;% filter,相关示例请参见?n():

data %>% group_by(col1) %>% filter(n() >= 3)

#Source: local data frame [3 x 2]
#Groups: col1 [1]

#    col1  col2
#   <chr> <chr>
#1 group1  some
#2 group1 some2
#3 group1 some3

将其包装在一个函数中:

allfiltered <- function(data, colgroup1) { 
    data %>% 
        group_by_(.dots = colgroup1) %>% 
        filter(n() >= 3) 
}

【讨论】:

  • 我觉得函数的使用更实用
【解决方案2】:

在基础 R 中,我们可以使用 split、Filter 和 rbind:

allfiltered <- function(df, colGroup) {

    d <- split(df, as.factor(df[, colGroup]))

    l <- Filter(function(l) nrow(l) >= 3, d)

    do.call(rbind, l)
}

这将data.frame拆分成data.frames的list,然后过滤满足条件的元素,最后解拆分列表:

allfiltered(data, 'col1')
# $group1
#    col1  col2
# 1 group1  some
# 2 group1 some2
# 3 group1 some3

【讨论】:

    猜你喜欢
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 2011-11-23
    • 1970-01-01
    相关资源
    最近更新 更多