簡體   English   中英

R for 循環多個變量

[英]R for loop over multiple variable

R 中在 Python 中循環這樣的 2 個向量的慣用方法是什么

for i,j in zip(Is, Js)

R中最明顯的方法是沿着索引

for (idx in seq_along(Is)) {
    i = Is[idx]
    j = Js[idx]

}

只是想知道是否有更不麻煩的方法?

編輯:

我正在使用 for 循環進行參數掃描,然后進行繪圖。 避免 for 循環的首選方法也將有所幫助。 所以例如

results = data.table()
for (threshold in c(2,3,4,5)) {
    largeRtn = rtn[abs(rtn)>threshold*volatility]
    results = rbind(results, someAnalysis(largeRtn) )
    qplot(largeRtn, ...)
}

像這樣的東西通常是類似 R 的:

func = function(a, b) {
    return(a*b)
}
a = c(2,3,1,7,8)
b = c(4,6,7,0,1)
mapply(func, a = a, b = b)
[1]  8 18  7  0  8

當然,在這種情況下,可以輕松地進行矢量化:

a * b
[1]  8 18  7  0  8

但在更復雜的情況下,矢量化可能不是一種選擇,那么您可以使用第一種方法。

也許我寫的這個教程可以幫助你。

我不確定你的 python 代碼是做什么的,但也許foreachiterators包是一個選項:

library(foreach)
library(iterators)

zip <- function(...) iter(obj = expand.grid(...), by = "row")
foreach(d = zip(i = 1:3, j = 5:10), .combine = c) %do% {d[,"i"] * d[,"j"]}
#[1]  5 10 15  6 12 18  7 14 21  8 16 24  9 18 27 10 20 30

當然,如果可能,您應該避免循環。

暫無
暫無

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

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