用foreach循环替换循环

时间:2018-03-12 13:31:48

标签: r foreach

我想要对我的代码进行分析,以便我可以利用所有核心。因此,我想用foreach循环替换for循环。由于我是R的前任,我无法理解这个主题的不同帖子如何解决这个问题。如果有人可以一步一步地帮助我(每行发表评论,以便我能理解它),那将是很棒的。下面是我的for循环,我想用foreach替换:

# A function used for Janshon-Shanon-Divergence computation, that I use inside my nested for loop
JensShanDiver = function(a,b) {
        m = 0.5 * (a + b)
        LRa = ifelse(a > 0, log2(a/m), 0)
        LRb = ifelse(b > 0, log2(b/m), 0)
        JSD = 0.5 * (sum(a * LRa) + sum(b * LRb))
        return(JSD)
}

#an empty dataframe having same dimensions as input dataframe
output <- data.frame(matrix(NA, nrow = nrow(input), ncol = ncol(input)))

#a vector of same length as of each row in input dataframe
v2 <- numeric(length(input[1,]))

for (j in 1:nrow(input)){
  #take each row from input df
   v1 <- as.numeric(input[j,])
   for(i in 1:length(v1)){
  # update an index value in the initially defined vector
    v2[i] <- 1
  # Take the sum of both vectors
    ifelse(v1[i] == 0, output_vec <- 1, output_vec <- JensShanDiver(v1, v2))
  # Reset the updated index to 0 again
    v2[i] <- 0
  # write the output value at [j,i]th index in the output dataframe 
    output[j,i] <- output_vec
   }
 }

输入数据帧的示例如下:

dput(input)
structure(c(0, 0.5, 0.5, 1, 0.333333333333333, 0.333333333333333, 
0.333333333333333, 0, 0, 1, 0, 0.5, 0.5, 0, 0.333333333333333, 
0.333333333333333, 0.333333333333333, 0.5, 0.5, 0, 1, 0, 0, 0, 
0.333333333333333, 0.333333333333333, 0.333333333333333, 0.5, 
0.5, 0), .Dim = c(10L, 3L), .Dimnames = list(NULL, c("ranges_in_X51214", 
"ranges_in_X56499", "ranges_in_X6383")))

以下是给定输入的预期输出:

> dput(output)
structure(list(X1 = c(1, 0.311278124459133, 0.311278124459133, 
0, 0.459147917027245, 0.459147917027245, 0.459147917027245, 1, 
1, 0), X2 = c(1, 0.311278124459133, 0.311278124459133, 1, 0.459147917027245, 
0.459147917027245, 0.459147917027245, 0.311278124459133, 0.311278124459133, 
1), X3 = c(0, 1, 1, 1, 0.459147917027245, 0.459147917027245, 
0.459147917027245, 0.311278124459133, 0.311278124459133, 1)), .Names = c("X1", 
"X2", "X3"), row.names = c(NA, 10L), class = "data.frame")

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

这是第一个去除内循环的过程 #!/bin/bash foo() { echo "user is $user, location is $location"; } eval "$(sed -e '/^$/s//foo/' input; echo foo)" 语句的构造不正确。我也不了解v2&lt; -1的目的,然后在两步之后了解v2&lt; -0。

ifelse

此输出与原始代码的输出匹配。正如上面的评论所说,可以进行额外的优化。