Home > database >  Translate python for-loop function into R
Translate python for-loop function into R

Time:10-01

I want to translate this python function into R. a is a list of numbers and the outcome should be 16/3. I appreciate any help!

def sum_differences(a):
    new_list = [abs(i-j) for i in a for j in a if i != j]
    outcome = sum(new_list) / len(a)
    return round(outcome,2)

This gives me 0:

sum_differences <- function(a){ 
  for (i in a){
    for (j in a){
        new_list <- abs(i-j)
        outcome <- sum(new_list) / length(a)
        return(round(outcome,2))
        }}}

a <- c(5, 3, 1)

CodePudding user response:

You may achieve this with outer -

a <- c(5, 3, 1)
sum(abs(outer(a, a, `-`)))/length(a)
#[1] 5.333

Or using a for loop -

outcome <- 0

for (i in a){
  for (j in a){
    new_list <- abs(i-j)
    outcome <- outcome   new_list
  }
}
outcome/length(a)
#[1] 5.333

CodePudding user response:

a <- c(5, 3, 1)

sum_differences <- function(a) {
  new_list <- c() 
  
  for (i in a) {
    for (j in a) {
      if(i != j) {
        new_list <- c(new_list, abs(i-j))
      }
    }
  }
  outcome = sum(new_list) / length(a)
  return(round(outcome, 2))
}

sum_differences(a)

[1] 5.33
  • Related