I am using a lme
object within a function but it does not use the response variable that I feed it, instead it uses the response variable from the previous time I called the function.
library(nlme)
library(car)
# DATA (Example)
S1=data.frame(blok = c(rep("blokI",16),rep("blokII",16)),
treat=rep(c("plus","plus","min","min"),8),
field = c(1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,14,14,15,15,16,16),
subfield = rep(c("a","b"),16),
var1=rnorm(32)^2,
var2=rnorm(32)^2)
S2=data.frame(blok = c(rep("blokI",16),rep("blokII",16)),
treat=rep(c("plus","plus","min","min"),8),
field = c(1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,14,14,15,15,16,16),
subfield = rep(c("a","b"),16),
var3=rnorm(32)^2,
var4=rnorm(32)^2)
# FUNCTION
get.stats = function(S,dofor){
U = data.frame(crop = NA, C = NA, T_S=NA, T_F=NA, T_DF=NA, T_P=NA, R_S=NA, R_F=NA, R_DF=NA, R_P=NA, TR_S=NA,TR_F=NA, TR_DF=NA, TR_P=NA)
for (i in 1:length(dofor)){
f = as.formula(paste(dofor[i]," ~ treat",sep=""))
model = lme(f, data=S, random = ~1|blok/treat/field/subfield)
av = Anova(model, type = "II")
U[i,1] = NaN
U[i,2] = dofor[i]
U[i,3] = av$`Chisq`[1]
U[i,4] = NaN
U[i,5] = av$Df[1]
U[i,6] = av$`Pr(>Chisq)`[1]
U[i,7] = av$`Chisq`[2]
U[i,8] = NaN
U[i,9] = av$Df[2]
U[i,10] = av$`Pr(>Chisq)`[2]
U[i,11] = av$`Chisq`[3]
U[i,12] = NaN
U[i,13] = av$Df[3]
U[i,14] = av$`Pr(>Chisq)`[3]
}
return(U)
}
dofor=c("var1","var2")
U = get.stats(S1, dofor) # First call of function
dofor=c("var3","var4")
U = rbind(U, get.stats(S2, dofor)) # Second call of function
If I call the function the first time I get Error in eval(x$call$fixed) : object 'f' not found
, which is already strange to me as f is defined within the function. I execute the command line where f is defined for i = 1
and call the function again. Now it works, but when I call the function a second time with S2
as data input I get the error:
Error in eval(predvars, data, env) : object 'var2' not found
I have to repeat this model for a many variables on yield of different crops for different years. With this function I intend to collect all the statistics for the different crop species in one matrix which I can latter edit in an Excel sheet.
Any suggestions on how to solve or by-pass my problem?