Graph of state occurrences in the paws

I run a simulation, I need to track the number of occurrences in a function call of a certain condition. I tried to accomplish this with an assignment to a global object. It works if you run the function, but if you try to execute the lapply function, as I do, you will get a single count of all the cases when this condition happened, and not a count for every time this happened for each item in the list fed to lapply .

Here is a fictitious situation where the occurrence is the uniformity of the number:

 FUN <- function(x){ lapply(1:length(x), function(i) { y <- x[i] if (y %% 2 == 0){ assign("count.occurrences", count.occurrences + 1, env=.GlobalEnv) } print("do something") }) list(guy="x", count=count.occurrences) } #works as expected count.occurrences <- 0 FUN(1:10) count.occurrences <- 0 lapply(list(1:10, 1:3, 11:16, 9), FUN) #gives me... #> count.occurrences #[1] 9 #I want... #> count.occurrences #[1] 5 1 3 0 

This is a simulation, so speed is a problem. I want it to be as fast as possible, so I am not married to the idea of ​​a global destination.

+4
source share
3 answers

Instead of assigning a global environment, why not just assign an internal FUN environment?

 FUN <- function(x){ count.occurances <- 0 lapply(1:length(x), function(i) { y <- x[i] if (y %% 2 == 0){ count.occurances <<- count.occurances + 1 } print("do something") }) list(guy="x", count=count.occurances) } Z <- lapply(list(1:10, 1:3, 11:16, 9), FUN) 

Then you can just pull out the counters.

 > sapply(Z, `[[`, "count") [1] 5 1 3 0 
+8
source

I have not tested this test, but have you tried just using a for loop? I know that loops are usually not encouraged in R, but they are also not always slower.

 FUN <- function(x) { count.occurrences = 0 for (i in 1:length(x)) { y = x[i] if (y %% 2 == 0) { count.occurrences = count.occurrences + 1 } print("do something") } list(guy="x", count=count.occurrences) } lapply(list(1:10, 1:3, 11:16, 9), FUN) 
+2
source

I can do it like this:

 count.occurances <- 0 Z <-lapply(list(1:10, 1:3, 11:16, 9), FUN) diff(c(0, sapply(1:length(Z), function(x) Z[[x]]$count))) 

I am open to better ideas (faster).

0
source

All Articles