R語言實現(xiàn)對數(shù)據(jù)框按某一列分組求組內(nèi)平均值
可使用aggregate函數(shù)
如:
aggregate(.~ID,data=這個數(shù)據(jù)框名字,mean)
如果是對數(shù)據(jù)框分組,組內(nèi)有重復(fù)的項,對于重復(fù)項保留最后一行數(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語言分組求和,分組求平均值,分組計數(shù)
我們經(jīng)??赡苄枰岩粋€數(shù)據(jù)按照某一屬性分組,然后計算一些統(tǒng)計值。在R語言里面,aggregate函數(shù)就可以辦到。
## S3 method for class 'data.frame' aggregate(x, by, FUN, ..., simplify = TRUE, drop = TRUE)
我們常用到的參數(shù)是:x, by, FUN。
x, 你想要計算的屬性或者列。
by, 是一個list,可以指定一個或者多個列作為分組的基礎(chǔ)。
FUN, 指定一個函數(shù),用來計算,可以作用在所有分組的數(shù)據(jù)上面。
假如這個是我們的數(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
分組求平均值
分組求平均很簡單,只要將上面的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
分組計數(shù)
分組計數(shù)就是在分組的情況下統(tǒng)計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
基于多個屬性分組求和。
我們在原有的數(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
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
R語言數(shù)可視化Split?violin?plot小提琴圖繪制方法
這篇文章主要為大家介紹了R語言數(shù)可視化Split?violin?plot小提琴圖繪制方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2022-02-02R包clusterProfiler如何安裝成功(新手必看!)
最近在我以為ClusterProfiler已經(jīng)安裝好的時候,又遇到了一些問題,所以這篇文章主要給大家介紹了關(guān)于R包clusterProfiler如何安裝成功的相關(guān)資料,需要的朋友可以參考下2023-02-02R語言繪圖數(shù)據(jù)可視化Ridgeline plot山脊圖畫法
這篇文章主要為大家介紹了R語言繪圖數(shù)據(jù)可視化Ridgeline plot山脊圖畫法的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助2022-02-02