R 基于固定组和高值对列进行分组

R 基于固定组和高值对列进行分组,r,dataframe,types,group-by,multiple-columns,R,Dataframe,Types,Group By,Multiple Columns,我试图根据预定义的组对数据表进行分组,这些组具有重叠信息。 分组和表格如下所示 我想1)检查df$Type是否包含group1或group2的所有元素 2) 检查组1或组2的所有元素的df$面积是否高于其他元素 3) 指定一个新列并为其标记所属的组 将组放入列表中 library(dplyr) ref <- list(Group1 = c("Bb","Ee","Xx"), Group2 = c("

我试图根据预定义的组对数据表进行分组,这些组具有重叠信息。 分组和表格如下所示

我想1)检查df$Type是否包含group1或group2的所有元素
2) 检查组1或组2的所有元素的df$面积是否高于其他元素
3) 指定一个新列并为其标记所属的组


将组放入列表中

library(dplyr)

ref <- list(Group1 = c("Bb","Ee","Xx"),
            Group2 = c("Ra","Xx"))

您可以将%中的
%用于(1)和(3)。问题2需要澄清。你的意思是找到最大值吗

问题1 问题3
df[df$Type%在%Group1,]$Group中
          ID Type Area Group
          1   Bb   19    G1
          1   Ee    5    G1
          1   Xx    4    G1
          2   Bb    1    G2
          2   Ra   10    G2
          2   Rb    1    G2
          2   Xx   20    G2
library(dplyr)

ref <- list(Group1 = c("Bb","Ee","Xx"),
            Group2 = c("Ra","Xx"))
get_group <- function(y, z) {
  Filter(function(x) {
    #1. check if Type has all elements of either group1 or group2
    if(all(x %in% y)) {
     inds  <- y %in% x
     if(any(!inds)) {
       #2. check if Area of all elements of either group1 or group2 
       #   is higher than other elements
       all(outer(z[inds], z[!inds], `>`))
     } else TRUE
    } else FALSE
    }, ref) -> res
  if(length(res) > 0) names(res)[1] else NA
}
df %>% group_by(ID) %>% mutate(Group = get_group(Type, Area)) %>% ungroup

#     ID Type   Area Group 
#  <dbl> <chr> <dbl> <chr> 
#1     1 Bb       19 Group1
#2     1 Ee        5 Group1
#3     1 Xx        4 Group1
#4     2 Bb        1 Group2
#5     2 Ra       10 Group2
#6     2 Rb        1 Group2
#7     2 Xx       20 Group2
> df$Type %in% union(Group1, Group2)
[1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE
df[df$Type %in% Group1,]$Group <- "G1"
df[df$Type %in% Group2,]$Group <- "G2"
> df
  ID Type Area Group
1  1   Bb   19    G1
2  1   Ee    5    G1
3  1   Xx    4    G2
4  2   Bb    1    G1
5  2   Ra   10    G2
6  2   Rb    1  <NA>
7  2   Xx   20    G2