📜  如何在 R 中使用聚合函数

📅  最后修改于: 2022-05-13 01:55:32.458000             🧑  作者: Mango

如何在 R 中使用聚合函数

在本文中,我们将讨论如何在 R 编程语言中使用聚合函数。

aggregate()函数用于按组获取数据的汇总统计信息。统计数据包括平均值、最小值、总和。最大等

语法

在哪里

  • 数据框是输入数据框。
  • aggregate_column 是要在数据框中聚合的列。
  • group_column 是要与 FUN 分组的列。
  • FUN 代表总和/平均值/最小值/最大值。

示例 1 :R 程序创建 4 列并按主题分组并获取最小值、总和和最大值等聚合。

R
# create a dataframe with 4 columns
data = data.frame(subjects=c("java", "python", "java",
                             "java", "php", "php"),
                  id=c(1, 2, 3, 4, 5, 6),
                  names=c("manoj", "sai", "mounika",
                          "durga", "deepika", "roshan"),
                  marks=c(89, 89, 76, 89, 90, 67))
  
# display
print(data)
  
# aggregate sum of marks with subjects
print(aggregate(data$marks, list(data$subjects), FUN=sum))
  
# aggregate minimum  of marks with subjects
print(aggregate(data$marks, list(data$subjects), FUN=min))
  
# aggregate maximum of marks with subjects
print(aggregate(data$marks, list(data$subjects), FUN=max))


R
# create a dataframe with 4 columns
data = data.frame(subjects=c("java", "python", "java",
                             "java", "php", "php"),
                  id=c(1, 2, 3, 4, 5, 6),
                  names=c("manoj", "sai", "mounika",
                          "durga", "deepika", "roshan"),
                  marks=c(89, 89, 76, 89, 90, 67))
  
# display
print(data)
  
# aggregate average of marks with subjects
print(aggregate(data$marks, list(data$subjects), FUN=mean))


输出

示例 2:创建 4 列并与主题分组并获得平均值(平均值)的 R 程序。

R

# create a dataframe with 4 columns
data = data.frame(subjects=c("java", "python", "java",
                             "java", "php", "php"),
                  id=c(1, 2, 3, 4, 5, 6),
                  names=c("manoj", "sai", "mounika",
                          "durga", "deepika", "roshan"),
                  marks=c(89, 89, 76, 89, 90, 67))
  
# display
print(data)
  
# aggregate average of marks with subjects
print(aggregate(data$marks, list(data$subjects), FUN=mean))

输出