将 python for 循环函数翻译成 R

Translate python for-loop function into R

我想将这个 python 函数翻译成 R。a 是一个数字列表,结果应该是 16/3。感谢您的帮助!

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)

这给了我 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)


您可以通过 outer -

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

或使用 for 循环 -

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

我们也可以 sapply

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