【问题标题】:R: Counting Text Mismatches Within Column Name Across a Series of ColumnsR:计算一系列列中列名中的文本不匹配
【发布时间】:2018-09-05 17:16:38
【问题描述】:

我有一组名称由多个项目组成的列,类似于:

df1<-data.frame(`apple,onion,pear`=0,`apple,banana,onion,pear`=0,`banana,pear`=0)

我在数据框中还有一组包含项目的列:

df2<-data.frame(thing_1=c('apple','onion','pear','banana'),thing_2=c('onion',NA,'banana','tree'),thing_3=c(NA,NA,'apple','pear'),thing_4=c(NA,NA,NA,'lobster'))

对于每个以 itemlist 命名的列,我想计算df2 的每一行中不存在于列名中的项目的计数。 NA 不应算作不匹配。真实数据集中存在数百行和数百列,但存在少量固定数量的thing_ 列。

所需的输出如下:

desiredresult<-data.frame(thing_1=c('apple','onion','pear','banana'),thing_2=c('onion',NA,'banana','tree'),thing_3=c(NA,NA,'apple','pear'),thing_4=c(NA,NA,NA,'lobster'),
                      'apple,onion,pear'=c(0,0,1,3),`apple,banana,onion,pear`=c(0,0,0,2),'banana,pear'=c(2,1,1,2))

作为逻辑的简要说明:

对于 apple.onion.pear 列,第 1 行是 0,因为 thing_1 中的“apple”和 thing_2 中的“onion”都出现在列名中,并且 NA 不会导致不匹配。第 3 行的值为 1,因为thing_2 是“香蕉”,它不会出现在列名中,而所有其他项目要么是 NA,要么可以在列名中找到。

到目前为止,我一直在与grepl() 合作,但我很难过!任何帮助将不胜感激。

【问题讨论】:

    标签: r string grepl


    【解决方案1】:

    tidyverse:

    library(tidyverse)
    
    strsplit(names(df1), split="\\.") %>%
      map2_dfc(syms(names(df1)),
               ~ transmute(df2, !!(.y) := apply(df2, 1, function(z) sum(!z %in% .x & !is.na(z))))) %>%
      bind_cols(df2, .)
    

    输出:

      thing_1 thing_2 thing_3 thing_4 apple.onion.pear apple.banana.onion.pear
    1   apple   onion    <NA>    <NA>                0                       0
    2   onion    <NA>    <NA>    <NA>                0                       0
    3    pear  banana   apple    <NA>                1                       0
    4  banana    tree    pear lobster                3                       2
      banana.pear
    1           2
    2           1
    3           1
    4           2
    

    【讨论】:

      猜你喜欢
      • 2020-01-08
      • 2020-12-18
      • 1970-01-01
      • 1970-01-01
      • 2016-04-21
      • 2022-06-21
      • 1970-01-01
      • 1970-01-01
      • 2017-03-07
      相关资源
      最近更新 更多