简体   繁体   English

函数输出到data.frame

[英]Output of a function into a data.frame

I have two functions: 我有两个功能:

c <- function(i, n=2009, t=2000){
  vect1 <- vector('numeric', length(t:n))
  w <- n-t
  for(q in 0:w){
    a <- 1/((1+i)^(q+1))
    b <- q+t
    vect1[q+1] <- a
  }
  return(vect1)
}

and

p <- function(i, n=2009, t=2000){
  w <- n-t
  for(q in 0:w){
    a <- c(i, n, q+t)
    print(a)
  } 
}

Upon defining both functions and running p(0.10), a table similar to the following is obtained, but it is printed. 在定义两个函数并运行p(0.10)时,将获得类似于以下内容的表,但该表将被打印。 I need the output in a data.frame so that I can join it with other data. 我需要在data.frame中输出,以便可以将其与其他数据连接起来。

0.909090909 0   0   0   0   0   0   0   0   0
0.826446281 0.909090909 0   0   0   0   0   0   0   0
0.751314801 0.826446281 0.909090909 0   0   0   0   0   0   0
0.683013455 0.751314801 0.826446281 0.909090909 0   0   0   0   0   0
0.620921323 0.683013455 0.751314801 0.826446281 0.909090909 0   0   0   0   0
0.56447393  0.620921323 0.683013455 0.751314801 0.826446281 0.909090909 0   0   
etc.

You could do something like this, which gives you a one-column data frame. 可以执行类似的操作,从而为您提供一个单列数据框。 I'm not exactly sure what you're trying to do, or to what other data you want to join this. 我不确定您要做什么,或者要加入哪些其他数据。 Maybe it will help you get to where you're trying to go: 也许它将帮助您到达要去的地方:

cFunc <- function(i, n=2009, t=2000){
  vect1 <- vector('numeric', length(t:n))
  w <- n-t
  for(q in 0:w){
    a <- 1/((1+i)^(q+1))
    b <- q+t
    vect1[q+1] <- a
  }
  return(vect1)
}

p <- function(i, n=2009, t=2000){
  w <- n-t
  a1 <- list()
  for(q in 0:w){
    q <- q+1
    a1[[q]] <- cFunc(i, n, q+t)
  } 
  return(a1)
}
listp <- p(0.10)
listp <- lapply(listp, as.data.frame)
listp <- data.table::rbindlist(listp, fill = TRUE)

Result: 结果:

> head(listp)
      X[[i]]
1: 0.9090909
2: 0.8264463
3: 0.7513148
4: 0.6830135
5: 0.6209213
6: 0.5644739

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

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