在 R 中创建一个数据框,它总结了所有独特的模式和它们存在的 类

Create a dataframe in R where it summarize all unique patterns and the classes which they exist

目前我正在处理一个数据集,我想知道哪些区域具有相同的模式。为了澄清这一点,我制作了一个输入数据集和一个输出数据集。

# Input data:
  Region F1 F2 F3
1      A  1  2  3
2      B  1  2  2
3      B  1  2  2
4      A  1  2  3
5      B  3  2  1
6      C  1  2  2
7      C  1  2  3
8      C  3  2  1
9      D  3  2  1

# Output data:
  F1 F2 F3 Number_Pattern Name_Region Total_Region
1  1  2  3              3        A, C            2
2  1  2  2              3        B, C            2
3  3  2  1              3     B, C, D            3

到目前为止,我只计算了输入数据集中有多少模式。我无法获取带有数字和名称的模式后面的特征区域(例如输出数据)。

library(dplyr)

# Input data
input <- data.frame(
  Region = c('A', 'B', 'B', 'A', 'B', 'C', 'C', 'C', 'D'),
  F1 = c(1, 1, 1, 1, 3, 1, 1, 3, 3),
  F2 = c(2, 2, 2, 2, 2, 2, 2, 2, 2),
  F3 = c(3, 2, 2, 3, 1, 2, 3, 1, 1)
)

output <- input %>%
  select(Region, F1, F2, F3) %>%
  group_by(F1, F2, F3) %>%
  dplyr::summarise(Number_Pattern =n(), .groups ='drop')

您可以使用unique获取一组中的所有unique Region并使用n_distinct来计算它。

library(dplyr)

input %>%
  group_by(F1, F2, F3) %>%
  #Or if there are many columns
  #group_by(across(starts_with('F'))) %>%
  summarise(Number_Pattern = n(), 
            Name_Region = toString(unique(Region)), 
            Total_Region  = n_distinct(Region))


#     F1    F2    F3 Number_Pattern Name_Region Total_Region
#  <dbl> <dbl> <dbl>          <int> <chr>              <int>
#1     1     2     2              3 B, C                   2
#2     1     2     3              3 A, C                   2
#3     3     2     1              3 B, C, D                3

这里有一个data.table方法

library( data.table )
setDT(input)[, .( Number_Pattern = .N, 
                  Name_Region = paste0( unique(Region), collapse = ", "),
                  Total_Region = uniqueN(Region) ), 
               by = .(F1, F2, F3) ]


# Output data:
#   F1 F2 F3 Number_Pattern Name_Region Total_Region
# 1  1  2  3              3        A, C            2
# 2  1  2  2              3        B, C            2
# 3  3  2  1              3     B, C, D            3

基本 R 中的相同逻辑:

output <- aggregate(
  Region ~F1 + F2 + F3, 
  input, 
  function(x) {y <-unique(x); c(Number_Pattern = length(x), Name_Region = toString(y), Total_Region = length(y))}
)
cbind(output[paste0("F", 1:3)], data.frame(output[[4]]))

#   F1 F2 F3 Number_Pattern Name_Region Total_Region
# 1  3  2  1              3     B, C, D            3
# 2  1  2  2              3        B, C            2
# 3  1  2  3              3        A, C            2