Pass condition as function parameter

Is there a way to pass a condition as a parameter? For instance:

#g is some data' getIndexesWhen <- function (colname, condition) { a <- as.vector(g[,colname]) a <- which(a fits condition) } 

And then it will be able to pass in the condition itself, for example. name something like getIndexesWhen('GDP','> 435') . Or I need to have separate functions for each case, for example. = ,! =,>, <, etc. <

+6
source share
3 answers

Instead of using an expression or function for "greater than 435", you can separate the "greater" and "435" part as arguments to your getIndexesWhen function:

 getIndexesWhen <- function(colname, fxn, rhs) { which(fxn(as.vector(g[,colname]), rhs)) } 

Now you can get the desired functionality without having to declare a custom function for each function pair / right side:

 g <- iris getIndexesWhen("Petal.Width", `<`, 0.2) # [1] 10 13 14 33 38 getIndexesWhen("Petal.Length", `==`, 1.5) # [1] 4 8 10 11 16 20 22 28 32 33 35 40 49 
+3
source

You can pass the function as a parameter:

 getIndexesWhen<-function(colname, condition) { a<-as.vector(g[,colname]) return(which(condition(a))) } getIndexesWhen("GDP", function(x)x>435) 
+3
source

Since you can convert a string to an executable expression, for example:

 eval(parse(text = "3 > 1")) 

Or, a line vector of executable expressions, using for example:

 sapply(parse(text = paste0(3:4, "<4")), eval) 

You can use this in your case to pass a free text condition using:

 getIndexesWhen<-function(g, colname, condition) { a <- as.vector(g[,colname]) which(sapply(parse(text = paste0(a, condition)), eval)) } 

This evaluates the column vector relative to the provided condition.

 g <- data.frame(C1 = c(2, 3, 4)) getIndexesWhen(g, "C1", ">=3") 
+1
source

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


All Articles