R函数仅打印向量的最后一个值
感谢您对此功能的帮助,该功能应该:
Thank you for your help with this function, which should :
- 输入一个特定值
- 将值插入函数
- 采用向量中生成的一组其他值
- 为向量的每个元素计算一个值
- 返回包含矢量和计算值的数据框.
这是我尝试过的:
rate<-function(Y2) {
ran<-seq(0.001,1,0.001)
for(i in ran) {
calculated<-as.vector(Y2/(1+i)+Y2/(1+i)^2+Y2/(1+i)^3+Y2/(1+i)^4)
tableau<-data.frame(ran,calculated)
}
return(tableau)
}
使用res<-rate(500)
进行测试时,仅最后一个值返回1000次:
When testing with res<-rate(500)
, only the last value is returned 1000 times:
...
ran calculated
1 0.001 468.75
2 0.002 468.75
3 0.003 468.75
...
996 0.996 468.75
997 0.997 468.75
998 0.998 468.75
999 0.999 468.75
1000 1.000 468.75
我的循环怎么了?
每次循环时,您要将as.vector(...)
计算的输出分配给相同的变量.然后,您将在每次循环时构建一个名为tableau
的data.frame.您只返回最后一次迭代.如果要保存每次迭代,则需要索引一些内容:
You're assigning the output of your as.vector(...)
calculation to the same variable each time you loop. Then you're building a data.frame, named tableau
each time you loop. You're only returning the last iteration. If you want to save each iteration, you'll need to index into something:
res[n] <- as.vector(...)
或更高级的R-ish版本,请使用Apply系列之一(特别是lapply
),并且完全没有循环:
Or the more R-ish version, use one of the apply family (specifically lapply
) and no loop at all:
rate <- function(Y2) {
ran <- seq(0.001, 1, 0.001)
result <- lapply(ran,
function(i) data.frame(ran = i,
calculated = as.vector(Y2/(1+i)+Y2/(1+i)^2+Y2/(1+i)^3+Y2/(1+i)^4)))
return (do.call(rbind, result))
}
话虽如此,没有理由要循环或套用功能.使用R
是矢量化的事实:
With that said, there is no reason for a loop or an apply function. Use the fact that R
is vectorized:
ran <- seq(0.001, 1, 0.001)
Y2 <- 500
calculated <- as.vector(Y2/(1+ran)+Y2/(1+ran)^2+Y2/(1+ran)^3+Y2/(1+ran)^4)
result <- data.frame(ran, calculated)
all.equal(result, rate(500))
# [1] TRUE