按因子按级别均值 [英] Mean by factor by level

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

问题描述

也许这很简单,但我在网上找不到答案.我在按级别按因子计算均值时遇到问题.我的数据看起来很典型:

Maybe this is simple but I can't find answer on web. I have problem with mean calculation by factors by level. My data looks typicaly:

factor, value
a,1
a,2
b,1
b,1
b,1
c,1

我想让向量 A 只包含a"级的平均值如果我在控制台上输入 A 我想得到 1.5而这种计算均值的方法,必须使用因子.

I want to get vector A contains mean only for level "a" If I type A on consol I want to get 1.5 And this method for calculating mean, must use factors.

预先感谢您的帮助.

推荐答案

发布 data.table 解决方案只是为了好玩,尽管您可能应该按照 @lukeA 的建议进行操作

Just for fun posting the data.table solution although you probably should do what @lukeA suggested

library(data.table) 
A <- setDT(df)[factor == "a", mean(value)]
## [1] 1.5

这篇关于按因子按级别均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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