簡體   English   中英

如何使用Apply函數而不是嵌套的for循環?

[英]How to use apply function instead of nested for loop?

我目前有一個大矩陣(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中用第一行和第一列中列出的不同參數在excel上打印f(x)的和。 我運行上面的代碼,它可以工作,但是需要很長時間。 我是Apply Function的新手,我是否知道如何使用Apply Function加快計算速度,並執行與上述相同的輸出?

這是您的問題的三行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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM