微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我做了一个将数据放入 data.frame 的函数,如何将这个 data.frame 从函数中拉出来?

如何解决我做了一个将数据放入 data.frame 的函数,如何将这个 data.frame 从函数中拉出来?

这是我做的一个函数。它并不复杂。基本上使用您输入的数据在数据表中制作向量并加起来一行。它吐出一个列表,它是一行和一个数据表的总和!

q4PV<- function(cfs,ttms,i) {
  cash_flows<-cfs 
  cash_flows<-data.frame(cash_flows)
  cash_flows$ttm<-ttms
  cash_flows$rates<-i/100
  cash_flows$present_values<-cash_flows$cash_flows*(1/(1+cash_flows$rates)^cash_flows$ttm)
  results<-list(Data=cash_flows,Total_Present_Value=sum(cash_flows$present_values))
  return(results)
}


# Here I gave it some info and it worked great!
q4PV(cfs=c(1100,-500,1900,1800,2000,100,1400,400,800),ttms=c(3,4,5,6,7,10,11,14,16,18),i=c(15,15,15))


# To my surprise,it spit this out,as I wanted:
$Data
   cash_flows ttm rates present_values
1        1100   3  0.15      723.26786
2        -500   4  0.15     -285.87662
3        1900   5  0.15      944.63580
4        1800   6  0.15      778.18967
5        2000   7  0.15      751.87408
6         100  10  0.15       24.71847
7        1400  11  0.15      300.92051
8        1900  14  0.15      268.52445
9         400  16  0.15       42.74591
10        800  18  0.15       64.64410

$Total_Present_Value
[1] 3613.644

这是我的问题,我是 R 的新手,能够使用这个表会很棒。但它是函数的局部,有没有办法解决这个问题?!所以我不必再创建另一个 data.table,因为它已经为我做了!

谢谢 亚伦 S

解决方法

在这里,没有必要创建一个函数。检查以下代码

library(data.table)
cfs = c(1100,-500,1900,1800,2000,100,1400,400,800)
ttms = c(3,4,5,6,7,10,11,14,16,18)
i = c(15,15,15)

DT <- data.table(cash_flows = cfs,ttm = ttms,rates = i/100)

# Create present_value column
DT[,present_value := cash_flows / (1 + rates)^ttm]

# DATA
DT[,.(cash_flows)]

# Total_present_Value
DT[,sum(present_value)]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。