I have a function that repeats a function until a certain value has been reached. For each repetition, a variable X changes and so should the result Y. I want to save every value that X and Y take as a dataframe.
get_Y <- function(X) {
Y <- Xˆ2
}
get_dataframe <- function() {
X <- 1
repeat {
get_Y(X)
X <- X*1.01
if (X > 2)
break
}
}
How do I save each X and Y to a dataframe, where each row is an iteration?
Here's a pretty efficient answer. The efficiency gains over your set up come in 2 main ways: (1) pre-calculate the length of the result so we can optimally (2) take advantage of the fact that get_Y
is vectorized, so we can call it on the entire input at once rather than one item at a time.
get_Y <- function(X) {
Y <- X^2
}
get_dataframe <- function() {
n = ceiling(log(2) / log(1.01))
X = cumprod(rep(1.01, n))
data.frame(X, Y = get_Y(X))
}
get_dataframe()
# X Y
# 1 1.010000 1.020100
# 2 1.020100 1.040604
# 3 1.030301 1.061520
# 4 1.040604 1.082857
# 5 1.051010 1.104622
# 6 1.061520 1.126825
# 7 1.072135 1.149474
# ...
# 65 1.909366 3.645680
# 66 1.928460 3.718959
# 67 1.947745 3.793710
# 68 1.967222 3.869963
# 69 1.986894 3.947749
# 70 2.006763 4.027099