将combn()函数应用于数据帧? [英] Applying combn() function to data frame?

查看:64
本文介绍了将combn()函数应用于数据帧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个数据框,其中包含不同股票的某些类型的数据,示例如下:

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
...

我要做的是使用combn()函数来计算2种股票的所有可能组合的乘积之和。我知道如何使用单个值来执行此操作,例如:

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?

谢谢

推荐答案

正如Alistaire所建议的,apply可以轻松地用于此

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

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

您还可以使用包 parallel 并使用 mcapply * 在多核模式下运行它的功能

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

这篇关于将combn()函数应用于数据帧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆