Applying combn() function to data frame?

…衆ロ難τιáo~ 提交于 2019-12-13 07:18:15

问题


so I have a data frame containing certain type of data for different stocks, sample as followed:

Date     RY    TD     BNS...
10-01   2.98   2.29   1.91
10-02   2.96   2.61   2.15
10-03   2.96   2.59   2.09
...

What I want to do is to use combn() function to calculate the sum of the products of all possible combinations of 2 stocks. I know how to do it with single values using, for example:

df <- c(2.98, 2.29, 1.91)
sum(combn(df, 2, prod))

But since now I have a data frame with daily data for each symbol, how do I apply the above function and output the sum results as a data list corresponding to each date?

Thanks


回答1:


As suggested by Alistaire, apply can be easily used for this

apply(df[, -1], 1, function(x) {
     sum(combn(x, 2, prod))
}
)

You could also use package parallel and use mcapply* functions to run it in multicore modes



来源:https://stackoverflow.com/questions/37192961/applying-combn-function-to-data-frame

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!