R:计算组子集的平均值 [英] R: Calculate means for subset of a group

查看:44
本文介绍了R:计算组子集的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算每个天"的平均值,但要计算一天中的一部分(时间=12-14).这段代码对我有用,但我必须每天输入一行新代码,这将达到数百行.

I want to calculate the mean for each "Day" but for a portion of the day (Time=12-14). This code works for me but I have to enter each day as a new line of code, which will amount to hundreds of lines.

这看起来应该很简单.当分组变量相同时,我很容易做到这一点,但当我不想包含当天的所有值时,我不知道该怎么做.有没有更好的方法来做到这一点?

This seems like it should be simple to do. I've done this easily when the grouping variables are the same but dont know how to do it when I dont want to include all values for the day. Is there a better way to do this?

sapply(sap[sap$Day==165 & sap$Time %in% c(12,12.1,12.2,12.3,12.4,12.5,13,13.1,13.2,13.3,13.4,13.5, 14), ],mean)

sapply(sap[sap$Day==166 & sap$Time %in% c(12,12.1,12.2,12.3,12.4,12.5,13,13.1,13.2,13.3,13.4,13.5, 14), ],mean)

数据如下所示:

Day Time    StomCond_Trunc
165 12      33.57189926
165 12.1    50.29437636
165 12.2    35.59876214
165 12.3    24.39879768

推荐答案

试试这个:

aggregate(StomCond_Trunc~Day,data=subset(sap,Time>=12 & Time<=14),mean)

这篇关于R:计算组子集的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆