我目前有一个大矩阵(3000x20),想要使用第一行和第一列中的值以及向量来计算值。我的数据集(在excel中)是这样的(我使用VBA代码来创建这个excel):
SumRow = 0
SumCol = 0
RowInterval = 0.001
ColInterval = 0.01
For i = 2 To 3001
Cells(i, 1).Value = SumRow + RowInterval
SumPD = Cells(i, 1).Value
Next i
For j = 2 To 21
Cells(1, j).Value = SumCol + ColInterval
SumRho = Cells(1, j).Value
Next j
我目前正在使用以下R代码进行计算
InputVector <- c(1,2,3,4,5,6,7,8,9,10)
Testing<-read.csv("InputFile.csv", header=FALSE)
for (m in (2:(3001)))
{ for (n in (2:21))
{ Sum = 0
Row = Testing(m,1)
Col = Testing(1,n)
for (p in (1:length(InputVector)))
{ Sum = Sum + sqrt((1-Col)/Col)*exp(Row) }
Testing[m,n] = Sum } }
write.csv(Testing, "TestingOutput.csv")
基本上它首先将一个向量(x值)放入公式f(x)中,我想在excel上打印f(x)的总和,并在excel的第一行和第一列中列出不同的参数。 我运行上面的代码,它的工作原理,但它需要很长时间。我是应用函数的新手,我可以知道如何使用apply函数来加速计算并执行与上面相同的输出吗?
答案 0 :(得分:0)
以下是针对您的问题的三线R解决方案,包括生成数据:
library(reshape2)
# generate the combinations to iterate over
vInput = seq(1, 10)
dfSeq = expand.grid(rowSeq = seq(from = 0, by = 0.001, length.out = 3000),
colSeq = seq(from = 0, by = 0.01, length.out = 20))
# generate the values
dfSeq = cbind.data.frame(result = mapply(function(row, col) {
length(vInput)*sqrt((1-col)/col)*exp(row)
}, dfSeq$rowSeq, dfSeq$colSeq), dfSeq)
# cast them in the shape required
dfSeqWide = dcast(dfSeq, rowSeq~colSeq, value.var = "result")