简体   繁体   中英

Save results on a loop in R

I am trying to run a code that saves the results of a for loop. Each time that the for loop runs, I want to save the values of landa and dlanda in a data frame called optimal with two columns one for the landa and the other for dlanda, but I do not know how to create this data frame called optimal inside the loop. This is my code:

Mean_Precipitation_July$mean_precip_monthYear
landa <- seq(0,1,by=0.1)
landa
(i <- 0)
(x <- 1)

for(i in landa) {

  T1 <- -(Mean_Precipitation_July$mean_precip_monthYear)^(landa)
  dlanda <- (mean(T1)-median(T1))/var(T1)
  optimal[x,1] <- landa
  optimal[x,2] <- dlanda
  
  i <- i + 0.1
  x<- x + 1

  
}

Here is a way. I use a fake test data set, since the OP has not posted one.

The test data vector is named data_vec .

set.seed(2020)
data_vec <- runif(20, 2, 5)
landa <- seq(0, 1, by = 0.1)


optimal <- matrix(nrow = length(landa), ncol = 2)
optimal <- as.data.frame(optimal)
names(optimal) <- c("landa", "dlanda")

for(i in seq_along(landa)) {
  T1 <- -(data_vec)^landa[i]
  dlanda <- (mean(T1) - median(T1))/var(T1)
  optimal$landa[i] <- landa[i]
  optimal$dlanda[i] <- dlanda
}
optimal
#   landa    dlanda
#1    0.0       NaN
#2    0.1 7.0957224
#3    0.2 3.0064453
#4    0.3 1.6915265
#5    0.4 1.0659035
#6    0.5 0.7129269
#7    0.6 0.4939882
#8    0.7 0.3498969
#9    0.8 0.2512264
#10   0.9 0.1817638
#11   1.0 0.1318914

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