我正在尝试存储下面函数的结果, 我只能打印结果但不能将其保存为csv格式。如何将这些结果保存到csv文件中? 在此先感谢!!!
calEAD=function(loan, R, final, startdate, first_enddate,enddate){
I=loan*R
start=as.Date(startdate)
firstend=as.Date(first_enddate)
p=firstend-start
period=as.numeric(p)/365
EADabc=0
b=enddate-2017
for(i in (0:b)){
EADabc=I/((1+R)**(i+period))+EADabc
print(EADabc)}
}
calEAD1=calEAD(6690012.88,0.0588,6690012.88, '2016-12-31','2017-08-29',2022)
calEAD2=calEAD(385000.12,0.0588,385000.12, '2016-12-31','2017-09-11',2023)
答案 0 :(得分:2)
似乎您希望将EADabc的每个中间结果保留在for循环中。在这种情况下,您可以将它们连接到这样的矢量:
calEAD=function(loan, R, final, startdate, first_enddate,enddate){
I=loan*R
start=as.Date(startdate)
firstend=as.Date(first_enddate)
p=firstend-start
period=as.numeric(p)/365
EADabc=0
b=enddate-2017
# Define an empty vector
result = c()
for(i in (0:b)){
EADabc=I/((1+R)**(i+period))+EADabc
# Append the current result to the vector
result = c(result,EADabc)
}
# Make the function return this vector
result
}
结果:
calEAD1=calEAD(6690012.88,0.0588,6690012.88, '2016-12-31','2017-08-29',2022)
calEAD2=calEAD(385000.12,0.0588,385000.12, '2016-12-31','2017-09-11',2023)
> calEAD1
[1] 378809 736581 1074484 1393622 1695037 1979713
> calEAD2
[1] 21755.57 42302.95 61709.24 80037.81 97348.51 113697.87 129139.28
如果要将它们保存到csv文件,请执行以下操作:
write.csv(x = calEAD1, file = "test.csv")
答案 1 :(得分:0)
您可以使用write.csv或write.table函数。
for(i in (0:b))
{
EADabc=I/((1+R)**(i+period))+EADabc
write.table(EADabc, file = "file_name.csv",sep = ",", col.names = T, append =T)
}
或者 write.csv(EADabc,file =" file_name.csv",row.names = FALSE)