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
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.