Josh. D
Josh. D

Reputation: 47

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. I need the output in a data.frame so that I can join it with other data.

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.

Upvotes: 0

Views: 35

Answers (1)

RobertMyles
RobertMyles

Reputation: 2832

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

Upvotes: 1

Related Questions