0
In the following dataset, I want to computer the function `rda` every 72 rows. Do this 10 times. Following [this solution][1] of lapply, I tried the same for a regression `rda`

set.seed(111)
df <- data.frame(sp1 = rep(rtruncnorm(10, a=0, b=1, mean = 0.50, sd = 0.2), times = 10),
                  sp2 = rep(rtruncnorm(10, a=0, b=1, mean = 0.70, sd = 0.1), times = 10),
                  env1 = rep(rtruncnorm(10, a=0, b=1, mean = 0.45, sd = 0.6), times = 10),
                  env2 = rep(rtruncnorm(10, a=0, b=1, mean = 0.65, sd = 0.6), times = 10)
                  )


library(vegan)
spe.rda  <- rda(df[,c(1:2)] ~ ., data = df[,c(3:4)]) #works fine without lapply

#Trying to loop it over the 10 seeds
spe.rda  <- lapply(split(df[1:4], df$seed), rda(df[,c(1:2)] ~ ., data = df[,c(3:4)]))

Error in match.fun(FUN) : 'rda(df[, c(1:2)] ~ ., data = df[, c(3:4)])' is not a function, character or symbol

Similarly, I tried applying the same to the ordiR2step function

output <- lapply(split(df[1:4], df$seed), 
ordiR2step(rda(df[,c(1:2)]~1, data=df[,c(3:4)]), scope= formula(spe.rda), direction= "forward", R2scope=TRUE, pstep=1000)) 
#Obviously it does not work as it's dependent on spe.rda
M--
  • 25,431
  • 8
  • 61
  • 93
Rspacer
  • 2,369
  • 1
  • 14
  • 40
  • You do not have `df$seed`. – Jari Oksanen Mar 08 '23 at 08:12
  • Secondly, your code creates 10 identical replicates of the data (`rep(rtruncnorm(10,...), times=10)` fixed result is repeated 10 times. You should use `as.vector(replicate(10, rtruncnorm(10, ...)))`) which will generate different random sequences. – Jari Oksanen Mar 08 '23 at 08:35

1 Answers1

1

Your example does not have df$seed: let's generate a bogus seed first:

## continuing with your example before first call to lapply
df$seed <- gl(10,10) # 10 groups, each 10 observations

Then call lapply with unnamed inline function:

lapply(split(df[1:4], df$seed), function(x) rda(x[,1:2] ~ ., data= x[,3:4]))
Jari Oksanen
  • 3,287
  • 1
  • 11
  • 15