Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

r - Calculate mean and median for a frequency table per column (length class per group)

I have a frequency table of length classes of fish per location:

LK   Loc1  Loc2  Loc3    
1     13   22     0          
2     20   18     4          
3     12   21     2          
4     2     0     1          
5     1     2     0        

I would like to calculate the mean and median value for each column (location) separately. For instance: Loc1: mean = (13 x 1)+(20 x 2)+(3 x 12)+(2 x 4)+(5 x 1)= 2.1 LK for Location 1.

I got really stuck on this and I don't know where to start. Is there a way to calculate this automatically for each column? Thank you in advance.

question from:https://stackoverflow.com/questions/65919086/calculate-mean-and-median-for-a-frequency-table-per-column-length-class-per-gro

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming your data is a data.frame df, for the mean

sapply(subset(df,select=-c(LK)),function(x){mean(x*df$LK)})

for the mean and median

sapply(subset(df,select=-c(LK)),function(x){c(mean(x*df$LK),median(x*df$LK))})

but perhaps you are searching for a weighted average of LK, each column containing the weights, in which case

sapply(subset(df,select=-c(LK)),function(x){weighted.mean(df$LK,x)})


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...