Get middle column A based on range of values ​​in column B

There are several columns in my data frame:

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

I have two conditions for getting average values ​​for column A.

  • Condition 1: I want to get the average value of column A when B is 1, that is, only rows 1 and row 2 will be averaged.
  • Condition 2: I want to get the average value of column B when the values ​​of column A are greater than 1 but less than 3, i.e. only line 2 will be considered.

I know that I can use a filter to crop a data frame only for column B = 1. However, I'm not sure how to do this when I want column B to be considered a range between 1 and 3.

Are there any smarter ways to get average column values ​​without first reducing the framework to a smaller size?

+6
source share
2 answers

You can make a subset in the same mean call as follows:

 with(df1, mean(A[B == 1])) with(df1, mean(B[A > 1 & A < 3])) 
+7
source

You can combine two logic tests with & . So you can combine test B > 1 with B < 3 :

 # Condition A: mean(df1$A[df1$B==1]) # Condition B: mean(df1$B[df1$A>1 & df1$A<3]) 
+2
source

Source: https://habr.com/ru/post/889104/


All Articles