【问题标题】:Is there a way to filter a DataFrame by unique variables stored in another DataFrame in R有没有办法通过存储在 R 中另一个 DataFrame 中的唯一变量来过滤 DataFrame
【发布时间】:2020-05-08 13:11:54
【问题描述】:

我正在尝试根据另一个数据框中的变量过滤嵌套数据框的列表,并在应用过滤器后为每个分组变量创建一个新的数据框。

样本数据集和组

combined <- data.frame(
  client = c('aaa','aaa','aaa','bbb','bbb','ccc','ccc','ddd','ddd'),
  type = c('norm','reg','opt','norm','norm','reg','opt','opt','opt'),
  age = c('>50','>50','75+','<25','<25','>50','75+','25-50','25-50'),
  IsActive = c('1','0','0','1','1','0','1','1','1')
)

# get unique variable combinations
unique_vars <- combined %>% 
  distinct() %>%
  group_split(client)

我认为unique_vars 中的变量组合可以应用于原始数据帧combined,以根据每个客户端的唯一变量创建单独的数据帧。我要创建的输出是原始数据框中每个客户端的每个变量组合及其唯一变量的数据框。例如,将基于unique_vars[1] 为客户端“aaa”创建 3 个数据帧,但基于unique_vars[4] 为客户端“ddd”创建仅 1 个数据帧,因为客户端“ddd”只有一行可能的变量组合

对最好的方法有什么建议吗?

【问题讨论】:

    标签: r dplyr purrr


    【解决方案1】:

    使用来自dplyrdistinct 命令

    split(distinct(combined),row.names(distinct(combined)))

    给予

    $`1`
      client type age IsActive
    1    aaa norm >50        1
    
    $`2`
      client type age IsActive
    2    aaa  reg >50        0
    
    $`3`
      client type age IsActive
    3    aaa  opt 75+        0
    
    $`4`
      client type age IsActive
    4    bbb norm <25        1
    
    $`5`
      client type age IsActive
    5    ccc  reg >50        0
    
    $`6`
      client type age IsActive
    6    ccc  opt 75+        1
    
    $`7`
      client type   age IsActive
    7    ddd  opt 25-50        1
    

    【讨论】:

      【解决方案2】:

      涉及dplyrpurrr 的选项可能是:

      map(.x = combined %>%
           distinct() %>%
           group_split(rowid = 1:n()),
          ~ combined %>%
           inner_join(.x))
      
      [[1]]
        client type age IsActive rowid
      1    aaa norm >50        1     1
      
      [[2]]
        client type age IsActive rowid
      1    aaa  reg >50        0     2
      
      [[3]]
        client type age IsActive rowid
      1    aaa  opt 75+        0     3
      
      [[4]]
        client type age IsActive rowid
      1    bbb norm <25        1     4
      2    bbb norm <25        1     4
      
      [[5]]
        client type age IsActive rowid
      1    ccc  reg >50        0     5
      
      [[6]]
        client type age IsActive rowid
      1    ccc  opt 75+        1     6
      
      [[7]]
        client type   age IsActive rowid
      1    ddd  opt 25-50        1     7
      2    ddd  opt 25-50        1     7
      

      【讨论】:

      • 这非常有效,是解决我问题的简单方法!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      • 2015-11-02
      • 1970-01-01
      • 2014-02-06
      • 2016-05-25
      • 2023-02-09
      • 1970-01-01
      相关资源
      最近更新 更多