Home > Enterprise >  Alternative nested 'for' loop R
Alternative nested 'for' loop R

Time:05-31

I have the following code, and I want to write it more efficiently. I couldn't figure out how to use the function mapplay in this case

a <- c(1,2,3)
b <- c(4,5,6)
M<- matrix(0,nrow=3,ncol=3)

for (i in 1:length(a)){
     shape= a[i]

     for (j in 1:length(b)){
     rate=b[i]

     X <- rgamma(100,shape,rate)
     M[i,j] <- ks.test(X,"pgamma",a,b)$p.value
      }
}

CodePudding user response:

It would be better if you'd provided code that worked (M is undefined) and defined your objective rather than providing a possible process.

Also, you might want to define what you mean by "efficient": minimum number of lines of code? Fastest execution? Most generalisable?

But in any case, here's a single pipe that I think does what you want.

library(tidyverse)

set.seed(123)

tibble() %>% 
  expand(
    shape=c(1,2,3), 
    rate=c(4,5,6), 
    X=rgamma(100,shape,rate)
  ) %>% 
  group_by(shape, rate) %>% 
  summarise(M=ks.test(X,"pgamma", shape, rate)$p.value, .groups="drop")
# A tibble: 9 × 3
  shape  rate        M
  <dbl> <dbl>    <dbl>
1     1     4 6.10e- 4
2     1     5 2.22e- 7
3     1     6 6.44e-11
4     2     4 1.34e- 4
5     2     5 4.43e- 2
6     2     6 4.41e- 1
7     3     4 0       
8     3     5 6.09e-12
9     3     6 1.02e- 7
  • Related