R - Loop to get ARMA coeftest output in list - r

R-newbie question.
I have some troubles understanding how to compute the coeftest function on ALL looped ARMA models and display the related output in the list.
How would you most simply adjust the following code?
library(lmtest)
bchain_2012_logreturns=diff(log(prices_2012))
bchain_2013_logreturns=diff(log(prices_2013))
bchain_logreturns_Arima_coef=list()
k=1
for(i in 2012:2013){
for(p in 0:1){
for(q in 0:1){
bchain_logreturns_Arima=Arima(get(paste("bchain_",i,"_logreturns",sep="")),order=c(p,0,q))
bchain_logreturns_Arima_coef[[k]]=round(transpose(coeftest(bchain_logreturns_Arima)),digit=3)
}
}
k=k+1
}

I did not understand how accumulator k works. Now it' fine.
library(lmtest)
bchain_2012_logreturns=diff(log(prices_2012))
bchain_2013_logreturns=diff(log(prices_2013))
bchain_logreturns_Arima_coef=list()
k=1
for(i in 2012:2013){
for(p in 0:1){
for(q in 0:1){
bchain_logreturns_Arima=Arima(get(paste("bchain_",i,"_logreturns",sep="")),order=c(p,0,q))
bchain_logreturns_Arima_coef[[k]]=round(transpose(coeftest(bchain_logreturns_Arima)),digit=3)
k=k+1
}
}
}

Related

R Error "missing value where TRUE/FALSE is needed" when using if-statement in a for-loop

This error occured in a code chunk of stochastic simulation.The entire chunk is as:
set.seed(123)
X=10000
S=c()
r1=runif(X,min=0,max=1)
n=qbinom(r1,5,0.5)
d<-c(0,1000,2000,3000)
u<-c(Inf,10000,20000,50000)
p<-c()
for(k in 1:4){
S<-c()
L<-c()
for (i in 1:X){
r2=runif(n[i],min = 0,max = 1)
x=qpareto(r2,shape=2.5,scale=3000)
z=c()
for (j in 1:length(x)){
if(x[j]<d[k]){z[j]=0}
}
S[i]=sum(x)
L[i]=sum(z)
}
p[k]=length(L[L>10000])/length(S)
}
And the error "missing value where TRUE/FALSE is needed" occurs in this part below.
for (j in 1:length(x)){
if(x[j]<d[k]){z[j]=0}
}
To see what's wrong with it I tried out some similar code as below, and it worked normally.
for(k in 1:4){
L=c()
for(j in 1:3){
x=runif(5,min=0,max=20000)
for(i in 1:5){
if(x[i]>d[k]){x[i]=x[i]-d[k]}
}
L[j]=sum(x)
}
print(L)
}
So I guess the problem lies in the length(x),but as a beginner I really have no idea why and how I can solve it...
Would be grateful for any suggestion! <3

R. Problem with a loop through character strings

I create this function to summarize the results of a glm:
outcome_forest<-function(mod,var,sd){
x<-summary(mod)
y<-x$coefficients
x_df<-as.data.frame(y)
x_df$Estimate<-x_df[var,1]/sd
x_df$ci_min<-x_df[var,1]-x_df[var,2]/sd
x_df$ci_max<-x_df[var,1]+x_df[var,2]/sd
return(x_df[var,c(1,5,6,4)])
}
Now I have different glm models:
mod_1<-glm(y_1~x_1+c_1+c_2,data=data_1, family = binomial)
mod_2<-glm(y_1~x_2+c_1+c_2,data=data_1, family = binomial)
I want to create a loop in order to pass my function to these two models:
thelist<-c("mod_1","mod_2")
sd<-c(0.58,0.98)
results<-list()
for(i in thelist){
for(j in sd){
results[[i]]<-outcome_forest(i,2,j)
}
}
I obtained the followin error
Error: $ operator is invalid for atomic vectors
I’m guessing this is happening because of the quota marks in model_1 and model_2. But these quotes are needed in order to create a thelist vector which just those names and no the results of both regression models.
How can I fix this issue?
You are correct, outcome_forest takes mod as an object, and you have it as a string c("mod_1","mod_2"). To make R evaluate that string as an object you need to use eval(parse(text=...)):
thelist<-c("mod_1","mod_2")
sd<-c(0.58,0.98)
results<-list()
for(i in thelist){
for(j in sd){
results[[i]]<-outcome_forest(eval(parse(text=i)),2,j)
}
}
But this approach isn't too god, its better to place the "mod"'s in a list and looping trough that:
l = list(mod_1, mod_2)
thelist<-c("mod_1","mod_2")
sd<-c(0.58,0.98)
results<-list()
for(i in 1:2){
for(j in sd){
results[[thelist[i]]]<-outcome_forest(l[[i]],2,j)
}
}
Or avoid creating thelist by naming results later:
sd<-c(0.58,0.98)
results<-list()
for(i in 1:2){
for(j in sd){
results[[i]]<-outcome_forest(l[[i]],2,j)
}
}
names(results) = c("mod_1","mod_2")

Use set.seed() with foreach() in R

I am currently running a simulation using a for loop in R, but want to switch over to a foreach loop since it is faster. I use set.seed() in the for loop, and would like to use this again with foreach so I can obtain identical results.
For example, suppose I have
x <- c()
for (i in 1:10){
set.seed(i)
x[i] <- rnorm(1)
}
How can I do this same thing using foreach? I don't think this works:
x <- foreach(i = 1:10, ...) %dopar% {set.seed(i) ... }
This works:
library (foreach)
fn<-function(i)
{
set.seed(i)
y <- rnorm(1)
return(y)
}
x<-foreach(i=1:10) %do% fn(i)
print(x)

Trying to use a for loop for population simulation(2)

Im sorry to say that I have a problem with a for loop, again. I'm trying to save the final number from a population estimate for loop into a new matrix but I am only able to get the population estimate to show up in row 100. I know it relates to breedingPop2 but I cant figure it out. Any help would be much appreciated. Please find the code below:
finalPop=matrix(nrow=102, ncol=1)
for(i in 1:100){
SWWAyears=data.frame(iteration=rep(NA,101),pop=NA)
breedingPop<-90000
fallMig<-.825
springMig<-.825
winterSurvival<-rbeta(100,.95,.05)
npFecund<-rbinom(100, 3.0, .9)
pFecund<-rbeta(100, .85,.25)
breedingSurvival<-rbeta(100,.95,.05)
# Set initial starting condition
SWWAyears[1,2]=breedingPop
for(years in 2:101) {
fallPop<-(SWWAyears[years-1,2]*fallMig)
for (i in 1:100){
winterPop<-(fallPop*winterSurvival[i])}
springPop<-(winterPop*springMig)
for (i in 1:100){
summerPop<-(springPop*breedingSurvival[i])
}
for(i in 1:100){
breedingPop2<-((summerPop*.26)*npFecund[i])+((summerPop*.14)*pFecund[i])+(summerPop*.60)
}
SWWAyears[years,1]=years
SWWAyears[years,2]<-breedingPop2
}
finalPop[i,1]<-breedingPop2
}
I think you have more fundamental issues with your looping structure and you're not getting the correct results you're expecting. However, the reason for your specific question about only the 100th row being updated is:
Your variable i is being updated inside your 'inner' for() loops, so by the time you reach finalPop[i, 1] <- breedingPop2, i always equals 100.
You need to use a different variable, j for example, in your inner for() loops.
finalPop=matrix(nrow=102, ncol=1)
for(i in 1:100){
SWWAyears = data.frame(iteration=rep(NA,101),pop=NA)
breedingPop <- 90000
fallMig <- .825
springMig <- .825
winterSurvival <- rbeta(100,.95,.05)
npFecund <- rbinom(100, 3.0, .9)
pFecund <- rbeta(100, .85,.25)
breedingSurvival <- rbeta(100,.95,.05)
# Set initial starting condition
SWWAyears[1,2] = breedingPop
for(years in 2:101) {
fallPop <- (SWWAyears[years-1,2]*fallMig)
for (j in 1:100){
winterPop <- (fallPop*winterSurvival[j])
}
springPop <- (winterPop*springMig)
for (j in 1:100){
summerPop <- (springPop*breedingSurvival[j])
}
for(j in 1:100){
breedingPop2 <- ((summerPop*.26)*npFecund[j])+((summerPop*.14)*pFecund[j])+(summerPop*.60)
}
SWWAyears[years,1] = years
SWWAyears[years,2] <- breedingPop2
}
finalPop[i,1] <- breedingPop2
}
Having said that, using multiple nested for() loops is generally not recommended in R; you should be able to use matrix multiplication / vectorisation to achieve the same result.
Other Issues
your values of winterPop and summerPop will only ever be fallPop * winterSurvival[100] and springPop * breedingSurvival[100] respectively. Is this what you intended?

Saving result of 10 fold in different excel files for each fold

I did 10-fold CV. I want to save the result (prediction) of each fold into separate excel file. So far by using this coding write.csv(predictions, 'test1.csv'), it only save the last fold result. How should I do?
for(i in 1:10)
{
testIndexes <- which(folds==i,arr.ind=TRUE)
testData <- CAMPUR[testIndexes, ]
#print(testData)
#flush.console()
trainData <- CAMPUR[-testIndexes, ]
#print(trainData)
#flush.console()
model <- NaiveBayes(DIS~., data=trainData, usekernel=TRUE)
predictions <- predict(model, testData[,1:2])
write.csv(predictions, 'test1.csv')
print(predictions)
flush.console()
c=confusionMatrix(predictions$class, testData$DIS)
print(c)
flush.console()
}
Thanks

Resources