简体   繁体   English

如何为 R 中的循环指定名称

[英]How to assign a name for a loop in R

How to assign the, like a1, for a list of results from the loop below.如何为以下循环的结果列表分配 ,如 a1。 I need to assign a name for it as I would like to bind it into other data frame.我需要为它分配一个名称,因为我想将它绑定到其他数据框。 The result of the loop below is a vector like the following下面循环的结果是一个像下面这样的向量

[1] 1 [1] 0.5406649 [1] 0.3004368 [1] 0.1719659 [1] 0.1016359 [1] 0.06217712 [1] 0.03945969 [1] 0.02602179 [1] 0.0178452 [1] 0.01272237 [1] 0.009415309 [1] 0.00721497 [1] 0.005706426 [1] 0.004641471 [1] 0.003868288 [1] 0.00329191 [1] 0.002851581 [1] 0.002507559 [1] 0.002233267 [1] 0.002010551 [1] 0.001826749 [1] 0.001672853 [1] 0.001542335 [1] 0.001430377 [1] 0.001333362 [1] 0.001248536 [1] 0.001173769 [1] 0.001107392 [1] 0.00104808 [1] 0.0009947707 [1] 0.0009466023 [1] 0.0009028692 [1] 0.0008629883 [1] 0.000826474 [1] 0.0007929186 [1] 0.0007619772 [1] 0.0007333567 [1] 0.0007068057 [1] 0.0006821081 [1] 0.0006590766 [1] 0.0006375484 [1] 0.000617381 [1] 0.0005984495 [1] 0.0005806438 [1] 0.0005638664 [1] 0.0005480309 [1] 0.0005330601 [1] 0.0005188852 [1] 0.0005054442 [1] 0.0004926818 [1] 0.0004805478


i<-0
while(i<0.501){
  k<-0:103
  lx<-table$lx
  v<-(1+i)^-(k+1)
  df<-data.frame(k,lx,v)
  df<-df %>% 
    mutate(px= lx/lx[1]) %>%
    mutate(q_xk = 1- (lead(lx)/lx)) %>%
    mutate(all=v*px*q_xk)
  print(sum(df$all[-c(101:nrow(df))]))
  # replace NA value =0
  #df[is.na(df)] <- 0
  #sum(df$all[-c(101:nrow(df))])
  i<-i+0.01
}

create an empty vector before you run the loop:在运行循环之前创建一个空向量:

vect = c()

and instead of :而不是:

print(sum(df$all[-c(101:nrow(df))]))

use:用:

vect = c(vect,sum(df$all[-c(101:nrow(df))])))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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