生物信息随笔

aggregate函数梳理数据框

2021-06-23  本文已影响0人  南之绿桑

aggregate函数是处理数据框的强大工具:
aggregate Function in R- A powerful tool for data frames

基本函数格式如下:

aggregate(x = any_data, by = group_list, FUN = any_function)

x: 要处理的数据框
by: list格式,与行对应,主要是将数据分组处理
FUN: 处理函数
Example 1: Compute Mean by Group Using aggregate Function计算组平均数

data <- iris
head(data)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa
aggregate(x = data[, colnames(data) != "Species"],             
          by = list(data$Species),
          FUN = mean)
     Group.1 Sepal.Length Sepal.Width Petal.Length Petal.Width
1     setosa        5.006       3.428        1.462       0.246
2 versicolor        5.936       2.770        4.260       1.326
3  virginica        6.588       2.974        5.552       2.026

FUN可以用其他的函数,比如sum,sd之类的。

NA的处理

可以忽略数据中的NA,如果没有这个选项,会产生NA值。

aggregate(x = data1[ , colnames(data1) != "Species"],       
          by = list(data1$Species),
          FUN = mean,
          na.rm = TRUE)
上一篇 下一篇

猜你喜欢

热点阅读