Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

filter values using this code "Filter(function(x) condition on x , Var )" but using condition based on values calculated value of var

Apologies, if this is a simple question. I’m trying to use "Filter(function(x) condition with x , Var )" to filter values in a variable. The only thing is I want to be able to use a manipulation of "x" in the condition. Here below is a simplistic example. In the below code, I want to filter values in variable that are greater than the mean of that variable.

Var1 = 1:10
Filter(function(x) x > mean(x) , Var1 )
> integer(0)

As you can see it doesn’t work the way expected. There are other ways to filter but I’d like to do it in this format. Is there a way to write the "mean(x)" within the function part to make this work? Any help greatly appreciated. Thanks

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The x is a single value as it is looped over each element of the vector so mean(x) is just x. Instead it would be mean(Var1).

Filter(function(x) x > mean(Var1), Var1 )
[1]  6  7  8  9 10

If we want to understand what the ‘x’ is, just use a print statement

Filter(function(x) print(x), Var1)
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
 [1]  1  2  3  4  5  6  7  8  9 10

This can be reused by wrapping in a function

f1 <- function(vec) {
      Filter(function(x) x > mean(vec), vec)
 }
f1(Var1)
[1]  6  7  8  9 10

Or use subset

subset(Var1, Var1 > mean(Var1))
[1]  6  7  8  9 10
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading