Reputation: 89
I created a 10x10 matrix where each column represents functions FUN1 to FUN10, and each row represents parameters P1 to P10.
a <- NULL
a <- rbind(a,(sapply(c(1:n), function(x) FUN1(data,P1,x))))
a <- rbind(a,(sapply(c(1:n), function(x) FUN1(data,P2,x))))
a <- rbind(a,(sapply(c(1:n), function(x) FUN1(data,P3,x))))
a <- rbind(a,(sapply(c(1:n), function(x) FUN1(data,P4,x))))
a <- rbind(a,(sapply(c(1:n), function(x) FUN1(data,P5,x))))
a <- rbind(a,(sapply(c(1:n), function(x) FUN1(data,P6,x))))
a <- rbind(a,(sapply(c(1:n), function(x) FUN1(data,P7,x))))
a <- rbind(a,(sapply(c(1:n), function(x) FUN1(data,P8,x))))
a <- rbind(a,(sapply(c(1:n), function(x) FUN1(data,P9,x))))
a <- rbind(a,(sapply(c(1:n), function(x) FUN1(data,P10,x))))
a <- rbind(a,(sapply(c(1:n), function(x) FUN2(data,P1,x))))
...
a <- rbind(a,(sapply(c(1:n), function(x) FUN2(data,P10,x))))
a <- rbind(a,(sapply(c(1:n), function(x) FUN3(data,P1,x))))
...
a <- rbind(a,(sapply(c(1:n), function(x) FUN3(data,P10,x))))
...
a <- rbind(a,(sapply(c(1:n), function(x) FUN10(data,P1,x))))
...
a <- rbind(a,(sapply(c(1:n), function(x) FUN10(data,P10,x))))
a <- as.vector(a)
MM <- matrix(a,nrow=10,byrow=FALSE)
How can i make this code shorter?
Upvotes: 1
Views: 83
Reputation: 887671
We can use expand.grid
to create a data.frame with all the combinations of sequence of 'n', the FUN
s, and "P" object names
n <- 10
d1 <- expand.grid(n = seq_len(n), f = paste0("FUN", 1:10),
p = paste0("P", 1:10), stringsAsFactors = FALSE)
then loop over the rows
, apply the function on the 'data', and unlist
the list
of output to a vector
a <- do.call(rbind, lapply(seq_len(nrow(d1)), function(i)
match.fun(d1$f[i])(data, get(d1$p[i]), d1$n[i])))
MM <- matrix(a, nrow = 10, byrow = FALSE)
Or this can be done with tidyverse
library(dplyr)
library(tidyr)
library(stringr)
crossing(n = seq_len(n), f = paste0("FUN", 1:10),
p = str_c("P", 1:10)) %>%
pmap(~ match.fun(..2)(data, get(..3), ..1)) %>%
unlist %>%
matrix(., nrow = 10, byrow = FALSE)
Upvotes: 1