How how can I display results for every period?

Viewed 35

I wrote a simple function. The problem is that I only see the final outcome. I would like to see each step results.

See an example here:

t0 <- 100
f1 <- function(x) x*(1.5)^30 

f1(t0)

#[1] 31447174

I would like to see diplayed the outcome for every power from 1 to 30:

[1] 150 (100*1.5)
[2] 225 (100*(1.5)^2)
...
[30] 31447174

How can I do it?

1 Answers

You could put an sapply in it.

t0 <- 100
f1 <- function(x) sapply(1:30, function(i) x*(1.5)^i) 

f1(t0)
# [1]      150.000      225.000      337.500      506.250      759.375     1139.062 ...

Or, probably better performing, use a vector as an exponent.

f1 <- function(x) x*(1.5)^(1:30) 
f1(t0)
# [1]      150.000      225.000      337.500      506.250      759.375     1139.062 ...
Related