简体   繁体   中英

Translate python for-loop function into R

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)

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

We may also do this with sapply

a <- c(5, 3, 1)
sum(abs(sapply(a, `-`, a)))/length(a)
[1] 5.333333

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM