简体   繁体   English

如何计算 R 中多列的回报

[英]How to compute returns for multiple columns in R

I have a data frame with in column 1 the dates and in columns 2 to 180 returns for stocks.我有一个数据框,第 1 列是日期,第 2 列到 180 列是股票回报。 I want to compute the returns for all stocks.我想计算所有股票的回报。 I have tried for loops however cannot find the right syntax.我尝试过 for 循环,但找不到正确的语法。 Should I maybe use apply function?我应该使用 apply function 吗? Help is appreciated.帮助表示赞赏。

colSums列和

To sum up the columns 2:180 you can and store it in another column of the data.frame you can do simply:总结 2:180 列,您可以将其存储在 data.frame 的另一列中,您可以简单地执行以下操作:

data$totalReturn <- colSums(data[,c(seq(2,180))])

rowSums行和

If you want to get the sum columwise, you can use the function rowSums, eg如果要按列计算总和,可以使用 function rowSums,例如

totalReturn <- rowSums(data[,c(seq(2,180))])

dplyr dplyr

If there are several entries (rows) for one day you should consider using the package dplyr and the functions group_by and summarize or the function aggregate .如果一天有多个条目(行),您应该考虑使用 package dplyr和函数group_bysummarize或 function aggregate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM