按类型列的列中的值过滤数据帧

时间:2018-01-19 23:30:52

标签: r dataframe

我知道有很多回答类似的问题。例如: Filter data.frame rows by a logical condition 。问题是当列的类型是列表时,这些答案不起作用。

事实上,我正在使用我使用库Yelp businesses dataset加载的jsonlite(展平结果)。其中一列(业务类别)是一个字符串列表。

> typeof(business_df["categories"])
[1] "list"
> business_df[1:3, "categories"]
[[1]]
[1] "Shopping"         "Shopping Centers"

[[2]]
[1] "Food"               "Soul Food"          "Convenience Stores" "Restaurants"       

[[3]]
[1] "Food"         "Coffee & Tea"

目前,我有这个可怕的解决方案:

filterByCategory <- function(category) {
  filtered_df <- cbind(businesses_df)
  if (category != "All") {
    filtered_df[, "belongs"] <-
      apply(filtered_df["categories"], 1, function(x)
        is.element(category, x[[1]]))
    filtered_df <<- subset(filtered_df, belongs)
  }
}

如您所见,我需要使用[[1]]语法访问该列。这就是为什么我认为这些解决方案都不起作用的原因:

# All rows returned 
business_df[category %in% business_df$categories]
subset(business_df, category %in% business_df$categories)
# No rows returned
business_df %>% filter(category %in% categories)

1 个答案:

答案 0 :(得分:2)

听起来您正在尝试过滤列表列包含特定值的数据框。

categories是一个向量列表。 map_lgl会将列表的每个元素(向量)映射为logical

library('tidyverse')

df <- tribble(
  ~rownum, ~categories,
        1, c('a', 'b'),
        2, c('c', 'd'),
        3, c('d', 'e')
)

# All rows containing the 'd' category
df %>%
  filter(map_lgl(categories, ~'d' %in% .)) %>%
  str
#> Classes ‘tbl_df’, ‘tbl’ and 'data.frame':    2 obs. of  2 variables:
#>  $ rownum    : num  2 3
#>  $ categories:List of 2
#>   ..$ : chr  "c" "d"
#>   ..$ : chr  "d" "e"