根据B列中的值范围获取平均A列 [英] get average column A based on a range of values in column B

查看:55
本文介绍了根据B列中的值范围获取平均A列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据框有几列,如下所示:

My dataframe has several columns as follows:

df1 <- data.frame(A = c(1,2,4), B=c(1,3,1), C=c(1,1,3))

我有两个条件来获取A列的平均值.

I have two conditions to get average values for column A.

  • 条件1:当B为1时,我想获取A列的平均值,即仅对row1和row2进行平均.
  • 条件2:当列A的值大于1但小于3时,即仅考虑第2行,我想获得列B的平均值.

我知道我可以使用过滤器将数据帧剪切为仅将B列设为1.但是,我不确定如何将B列视为1到3之间的范围.

I know I can use filter to cut the dataframe to have column B = 1 only. However, I am unsure how to do it when I want the column B to be considered as a range within 1 and 3.

有没有更聪明的方法来获取列的平均值而不先将数据框切成更小的尺寸?

Are there any smarter ways to get the average values of column without cutting the dataframe into a smaller size first?

推荐答案

您可以在对mean的同一调用中进行子设置,如下所示:

You can do your subsetting in the same call to mean like so:

with(df1, mean(A[B == 1]))

with(df1, mean(B[A > 1 & A < 3]))

这篇关于根据B列中的值范围获取平均A列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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