Home > Net >  for loop in r with two condition to find the sum of difference
for loop in r with two condition to find the sum of difference

Time:08-14

I'm trying to write a code that has Two condition

function1 <- function(x,y){
x<- c(3,4,7)
y<-c(1,2,7)
diffsum<-0
for (i in 1:length(x))
  for(j in 1:length(y)){
    diffsum <- diffsum (x[i]-y[j])
  }
return(diffsum)
}

function1(x,y)
[1] 12

loking for (3-1) (4-2) (7-7) the result should be 4

CodePudding user response:

Just do sum(x-y). No need for any loop here.

If it has to be a loop:

function1 <- function(x,y)
{
  difftime <- 0
    
  for (i in 1:length(x))
  {
    loop_diff <- x[i] - y[i]
    difftime <- difftime   loop_diff
  }
  return(difftime)
}
  •  Tags:  
  • r
  • Related