【问题标题】:Filtering a dataframe by list of character vectors按字符向量列表过滤数据帧
【发布时间】:2020-12-17 21:19:05
【问题描述】:

我正在尝试根据字符向量列表过滤数据帧,并获取每个向量的输出。这是一个澄清我的问题的例子:

这是我拥有的数据类型

fruit <- c("Apple", "Banana", "Cherry")
vegetable <- c("Leek", "Courgette")
ls <- list(fruit, vegetable)
df <- data.frame(type = c("Apple", "Courgette", "Cherry"), 
                 quantity = c(10, 5, 3))                                  

我想使用列表ls 过滤我的数据框df 以获得一个列表或过滤的新数据框。输出的格式并不重要,我最终需要的信息是找出在df 中可找到的每个列表元素的比例。在数字上,那将是: 在数据框 df(Apple 和 Cherry)中只有 66.67% 的 fruit 值,在数据框(Courgette)df 中只有 50% 的 vegetable 值。在数据集/列表格式中,例如可以采用以下形式:

> new_df_fruit
    type
1  Apple
2 Cherry

> new_df_vegetable
       type
1 Courgette                       

从这个问题中获得灵感:R: "Filter" columns in a data frame by a list,我尝试运行代码

newDF <- df[which((names(df) %in% fruit ==TRUE)),]

但这不起作用,我不确定如何使用整个列表作为输入并接收另一个列表或一堆新数据集作为输出。 谢谢!

【问题讨论】:

  • 66%和50%是怎么得到的
  • 对于水果向量,它是 66%,因为向量中存在的 3 个值中有 2 个也存在于 df 中。 50% 是因为 2 个值中有 1 个也在 df 中。

标签: r list filter


【解决方案1】:

试试这个:

#Code
L <- lapply(ls,function(x) data.frame(type=x[x %in% df$type]))
names(L) <- paste0('new_df_',c('fruit','vegetable'))

输出:

L
$new_df_fruit
    type
1  Apple
2 Cherry

$new_df_vegetable
       type
1 Courgette

【讨论】:

    【解决方案2】:

    我们可以在lssubset 'df' 上使用循环,使用list2env 创建新对象

    list2env(setNames(lapply(ls, function(x) subset(df, 
         type %in% x, select = type)),
             paste0('new_df_', c('fruit', 'vegetable'))), .GlobalEnv)
    

    -输出

    new_df_fruit
    #    type
    #1  Apple
    #3 Cherry
    
    new_df_vegetable
    #       type
    #2 Courgette
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      • 2017-08-17
      • 2011-08-28
      • 2022-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多