2015-07-13 51 views
-1

我希望创建一个嵌套的foreach循环,以便外部循环执行一个函数并将此输出提供给嵌套的foreach循环。我只想为内部循环使用%dopar%,输出应该是来自外部foreach循环的每次迭代的列组合数组。代码如下:将函数的输出从函数输入到嵌套的foreach循环中R

data <- readLines('listofthings.txt') ##this is the master list 
h <- as.vector(words(length=6,alphabet=s2c("ACGT"))) ##this is an array of six-lettered words that I want to search in data1 below 

foreach (i = 1:length(data),.packages=c("ade4","seqinr")) %:% 
data1 <- s2c(c2s(data[i])) ##this converts the string to characters & is every item in the master 'data' list 
g <- foreach (j = 1:length(data1),.packages=c("ade4","seqinr"),.combine=cbind) %dopar% { 
    g[which(h==c2s(data1[j:(j+5)]))]+1 ##adds +1 to the same row which has the six letter word as h 
} 

所以,我希望代码将data1送入内部循环,然后执行后续操作。我已经写了每一步在评论中所做的事情,并且可能仍然令人困惑。我只想知道如何编写一个嵌套的foreach循环,以便外循环将函数的输出提供给内部foreach循环。

谢谢!

回答

0

foreach接受它在函数参数的第一个元素中传递的数据,在?foreach的帮助文件中名为“...”。这些是元素foreach迭代。下面我创建一个包含向量列表的例子,但这些向量可以很容易地成为数据框架,矩阵或您拥有的东西。

library(foreach) 

ml <- list(el1 = rnorm(10), el2 = rnorm(20), el3 = rnorm(30)) 

foreach(i = ml) %do% length(i) 

[[1]] 
[1] 10 

[[2]] 
[1] 20 

[[3]] 
[1] 30