简体   繁体   中英

how to store nested loop values in a matrix in r

I created a loop to calculate the following formula: values = 1+PE - (1+(i^w))^(1/w)) where PE and w change as follows:

#creation of my variables
w <- seq(1, 4, by = 0.1)
PE <- seq(1, 2, by = 0.1)

#creation of a matrix where I will be storing the results of the loop

results <- matrix(nrow= length(PE) , ncol= length(w))

#loop where w and PE are changing 

for(i in PE){
  for (j in w){
    results <- (1+i - (1+(i^j))^(1/j))
    print (results)
  }
}

results

If I run it I obtain a list where all my values are printed, but I face 2 problems:

i) I cannot store those values. When I print results outside the loop, I obtain 1 value and not all of them. So i cannot manipulate them to create a matrix and neither a data frame.

ii) I initially created a matrix for those values to be stored so when I add in the loop: results[i, j] I get several matrices with many NA values when I should be getting only one matrix. And this matrix should have 11 rows and 31 columns

TABLE

results[i,j] the way you defined doesn't work because i and j are not indexes, but values, so you won't get results[1,1], results[1,2], ... but the values of PE and w instead. For that to work you should use i and j as indexes by doing 1:length(PE) , and getting the terms of PE by PE[i] , and the same for w .

for(i in 1:length(PE)){
  for (j in 1:length(w)){
    results[i,j] <- (1+PE[i] - (1+(PE[i]^w[j]))^(1/w[j]))
  }
}
w <- seq(1, 4, by = 0.1)
PE <- seq(1, 2, by = 0.1)

results <- sapply(w, function(j) (1+PE - (1+(PE^j))^(1/j)))

for(i in 1:length(PE)){
  for (j in 1:length(w)){
    results[i,j] <- (1+PE[i] - (1+(PE[i]^w[j]))^(1/w[j]))
  }
}

results 

write.table (results, file = "results.csv", sep = ",")


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM