I have a question that must surely seem very trivial, but the answer has always alluded me: how do you print values for multiple variables on the same line from within a for-loop?
I present two solutions neither of which relies on nothing more than a formatted print
statement, and I am still interested in whether print
can, by itself, be used to return output in the desired format.
First I present the for-loop
, which contains one solution, and then I present a function that represents another solution:
P <- 243.51
t <- 31 / 365
n <- 365
for (r in seq(0.15, 0.22, by = 0.01)) {
A <- P * ((1 + (r/ n))^ (n * t))
interest <- A - P
# this prints each variable on a separate line
print (r)
print (interest)
# this does not work
# print c(r, interest)
# this presents both variables on the same line, as desired
output <- c(r,interest)
print(output)
# EDIT - I just realized the line below prints output in the desired format
print (c(r, interest))
}
# this function also returns output in the desired format
data.fn <- function(r) {
interest <- P*(1+(r/ n))^(n*t) - P
list(r = r, interest = interest)
}
my.output <- as.data.frame(data.fn(seq(0.15, 0.22, by = 0.01)))
my.output
# r interest
# 1 0.15 3.121450
# 2 0.16 3.330918
# 3 0.17 3.540558
# 4 0.18 3.750370
# 5 0.19 3.960355
# 6 0.20 4.170512
# 7 0.21 4.380842
# 8 0.22 4.591345
Is there a way to format print
statements in the for-loop
so that the print
statement, by itself, returns output formatted as in my.output
? I know that I could also place a matrix inside the for-loop that stores the values of r
and interest
and then print the matrix after the loop finished. However, I thought using a print
statement would be easier, especially since I do not need to retain the values of r
or interest
.
Thank you for any advice. Sorry again this question is so trivial. I have searched quite a bit for the answer over an extended period, but have never found the solution. Maybe I have presented enough solutions in this post to make additional possible solutions overkill. Nevertheless, I remain interested.
EDIT:
In addition to the helpful responses below I just realized that using:
print (c(r, interest))
in the above for-loop
also works.