欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

R語言實(shí)現(xiàn)對(duì)數(shù)據(jù)框按某一列分組求組內(nèi)平均值

 更新時(shí)間:2021年03月16日 15:48:26   作者:faith默默  
這篇文章主要介紹了R語言實(shí)現(xiàn)對(duì)數(shù)據(jù)框按某一列分組求組內(nèi)平均值,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧

可使用aggregate函數(shù)

如:

aggregate(.~ID,data=這個(gè)數(shù)據(jù)框名字,mean) 

如果是對(duì)數(shù)據(jù)框分組,組內(nèi)有重復(fù)的項(xiàng),對(duì)于重復(fù)項(xiàng)保留最后一行數(shù)據(jù)用:

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

補(bǔ)充:R語言分組求和,分組求平均值,分組計(jì)數(shù)

我們經(jīng)??赡苄枰岩粋€(gè)數(shù)據(jù)按照某一屬性分組,然后計(jì)算一些統(tǒng)計(jì)值。在R語言里面,aggregate函數(shù)就可以辦到。

## S3 method for class 'data.frame'
aggregate(x, by, FUN, ..., simplify = TRUE, drop = TRUE)

我們常用到的參數(shù)是:x, by, FUN。

x, 你想要計(jì)算的屬性或者列。

by, 是一個(gè)list,可以指定一個(gè)或者多個(gè)列作為分組的基礎(chǔ)。

FUN, 指定一個(gè)函數(shù),用來計(jì)算,可以作用在所有分組的數(shù)據(jù)上面。

假如這個(gè)是我們的數(shù)據(jù)。

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

分組求和

 aggregate(df$value, by=list(type=df$type),sum)
 type  x
1  a 208
2  b 115
3  c 118
4  d 22

分組求平均值

分組求平均很簡(jiǎn)單,只要將上面的sum改成mean就可以了。

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

分組計(jì)數(shù)

分組計(jì)數(shù)就是在分組的情況下統(tǒng)計(jì)rows的數(shù)目。

aggregate(df$value, by=list(type=df$type),length)
 type x
1  a 3
2  b 3
3  c 3
4  d 1

基于多個(gè)屬性分組求和。

我們?cè)谠械臄?shù)據(jù)上加上一列,可以看看多屬性分組。

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

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。

相關(guān)文章

最新評(píng)論