I have a data frame with in column 1 the dates and in columns 2 to 180 returns for stocks. I want to compute the returns for all stocks. I have tried for loops however cannot find the right syntax. Should I maybe use 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:
data$totalReturn <- colSums(data[,c(seq(2,180))])
rowSums
If you want to get the sum columwise, you can use the function rowSums, eg
totalReturn <- rowSums(data[,c(seq(2,180))])
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.