我有一个肯定看起来非常微不足道的问题,但答案一直提到我:如何在for-loop中打印同一行上的多个变量的值?
我提出了两种解决方案,它们都不仅仅依赖于格式化print语句,而且我仍然感兴趣的是print,它本身是否可以用于以所需格式返回输出.
首先我提出for-loop包含一个解决方案的,然后我提出一个代表另一个解决方案的函数:
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
Run Code Online (Sandbox Code Playgroud)
有没有办法格式化print语句,for-loop以便print语句本身返回格式为的输出my.output?我知道,我也可以把矩阵中的for循环存储的值内r和interest然后打印矩阵中的循环结束后.但是,我认为使用print语句会更容易,特别是因为我不需要保留r或的值interest.
谢谢你的任何建议.再次抱歉,这个问题非常简单.我在很长一段时间内搜索了相当多的答案,但从未找到解决方案.也许我已经在这篇文章中提出了足够的解决方案来提供额外的可能解决方案.不过,我仍然感兴趣.
编辑:
除了下面的有用回复,我才意识到使用:
print (c(r, interest))
Run Code Online (Sandbox Code Playgroud)
在上面for-loop也有效.
Tej*_*til 21
尝试cat和sprintf你的for循环.
例如.
cat(sprintf("\"%f\" \"%f\"\n", df$r, df$interest))
Run Code Online (Sandbox Code Playgroud)
看到这里
| 归档时间: |
|
| 查看次数: |
92777 次 |
| 最近记录: |