[英]get average column A based on a range of values in column B
My dataframe has several columns as follows:我的 dataframe 有几列如下:
df1 <- data.frame(A = c(1,2,4), B=c(1,3,1), C=c(1,1,3))
I have two conditions to get average values for column A.我有两个条件来获取 A 列的平均值。
I know I can use filter to cut the dataframe to have column B = 1 only.我知道我可以使用过滤器将 dataframe 切割为只有 B = 1 列。 However, I am unsure how to do it when I want the column B to be considered as a range within 1 and 3.
但是,当我希望将 B 列视为 1 和 3 之间的范围时,我不确定该怎么做。
Are there any smarter ways to get the average values of column without cutting the dataframe into a smaller size first?有没有更聪明的方法来获得列的平均值而不先将 dataframe 切成更小的尺寸?
You can do your subsetting in the same call to mean
like so:您可以在同一个调用中进行子集设置,以
mean
如下:
with(df1, mean(A[B == 1]))
with(df1, mean(B[A > 1 & A < 3]))
You can combine two logical tests with &
.您可以将两个逻辑测试与
&
结合起来。 So you could combine the B > 1
test with B < 3
:因此,您可以将
B > 1
测试与B < 3
结合起来:
# Condition A:
mean(df1$A[df1$B==1])
# Condition B:
mean(df1$B[df1$A>1 & df1$A<3])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.