Replacing for loop with foreach loop

前端 未结 1 1993
温柔的废话
温柔的废话 2020-12-12 03:26

I want to parellelize my code so that I can utilize all the cores. Therefore, I want to replace the for loop with foreach loop. As I am begginner to R, I could not understan

相关标签:
1条回答
  • 2020-12-12 03:46

    Here is a first pass which removes the inner loop.
    The construction of the ifelse statement was incorrect. I also don't understand the purpose of v2<-1 and then v2<-0 two steps later.

    input<-read.table(header=TRUE, text ="ranges_in_X51214 ranges_in_X56499 ranges_in_X6383
    0.0              0.0               1
    0.5              0.5               0
    0.5              0.5               0")
    
    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,]))
    v2 <- 1
    for (j in 1:nrow(input)){
      #take each row from input df
      v1 <- as.numeric(input[j,])
      # Take the sum of both vectors
      output_vec<-ifelse(v1 == 0,  1, sum(v1)+1)
      # write the output value at j row
      output[j,] <- output_vec
    }
    

    This output matches the output of the original code. As the comments above say there is additional optimization which can be done.

    0 讨论(0)
提交回复
热议问题