可使用aggregate函數
如:
1
|
aggregate(.~ID,data=這個數據框名字,mean) |
如果是對數據框分組,組內有重復的項,對于重復項保留最后一行數據用:
1
2
3
|
pcm_df$duplicated <- duplicated( paste (pcm_df$OUT_MAT_NO, pcm_df$Posit, sep = "_" ), fromLast = TRUE) pcm_df <- subset(pcm_df, !duplicated) pcm_df$duplicated <- NULL |
補充:R語言分組求和,分組求平均值,分組計數
我們經常可能需要把一個數據按照某一屬性分組,然后計算一些統計值。在R語言里面,aggregate函數就可以辦到。
1
2
|
## S3 method for class 'data.frame' aggregate(x, by, FUN, ..., simplify = TRUE, drop = TRUE) |
我們常用到的參數是:x, by, FUN。
x, 你想要計算的屬性或者列。
by, 是一個list,可以指定一個或者多個列作為分組的基礎。
FUN, 指定一個函數,用來計算,可以作用在所有分組的數據上面。
假如這個是我們的數據。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
type <-c( "a" , "b" , "c" , "a" , "c" , "d" , "b" , "a" , "c" , "b" ) value<-c(53,15,8,99,76,22,46,56,34,54) df <-data.frame( type ,value) df type value 1 a 53 2 b 15 3 c 8 4 a 99 5 c 76 6 d 22 7 b 46 8 a 56 9 c 34 10 b 54 |
分組求和
1
2
3
4
5
6
|
aggregate( df $value, by=list( type = df $ type ), sum ) type x 1 a 208 2 b 115 3 c 118 4 d 22 |
分組求平均值
分組求平均很簡單,只要將上面的sum改成mean就可以了。
1
2
3
4
5
6
|
aggregate( df $value, by=list( type = df $ type ),mean) type x 1 a 69.33333 2 b 38.33333 3 c 39.33333 4 d 22.00000 |
分組計數
分組計數就是在分組的情況下統計rows的數目。
1
2
3
4
5
6
|
aggregate( df $value, by=list( type = df $ type ),length) type x 1 a 3 2 b 3 3 c 3 4 d 1 |
基于多個屬性分組求和。
我們在原有的數據上加上一列,可以看看多屬性分組。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
type_2 <-c( "F" , "M" , "M" , "F" , "F" , "M" , "M" , "F" , "M" , "M" ) df <- data.frame( df , type_2) df type value type_2 1 a 53 F 2 b 15 M 3 c 8 M 4 a 99 F 5 c 76 F 6 d 22 M 7 b 46 M 8 a 56 F 9 c 34 M 10 b 54 M aggregate(x= df $value, by=list( df $ type , df $type_2), sum ) Group.1 Group.2 x 1 a F 208 2 c F 76 3 b M 115 4 c M 42 5 d M 22 |
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。如有錯誤或未考慮完全的地方,望不吝賜教。
原文鏈接:https://blog.csdn.net/faith_mo_blog/article/details/50738645