根据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]))