在 R 中编写中值函数

Writing a median function in R

我的任务是在不使用内置中值函数的情况下,在 R 中编写自己的中值函数。如果数字是奇数;计算两个中间值,就像通常计算中值一样。 我可能可以在 Java 中做一些事情,但我在

中遇到一些语法问题

R代码:

list1 <- c(7, 24, 9, 42, 12, 88, 91, 131, 47, 71)

sorted=list1[order(list1)]
sorted
n = length(sorted)
n
if(n%2==0) # problem here, implementing mod() and the rest of logic.

这里是自己写的函数mymedian:

mymedian <- function(lst) {
  n <- length(lst)
  s <- sort(lst)
  ifelse(n%%2==1,s[(n+1)/2],mean(s[n/2+0:1]))
}

例子

list1 <- c(7, 24, 9, 42, 12, 88, 91, 131, 47, 71)
list2 <- c(7, 24, 9, 42, 12, 88, 91, 131, 47)
mymedian(list1)
mymedian(list2)

这样

> mymedian(list1)
[1] 44.5

> mymedian(list2)
[1] 42

我相信这应该能让您得到您正在寻找的中位数:

homemade_median <- function(vec){
  sorted <- sort(vec)
  n <- length(sorted)
  if(n %% 2 == 0){
    mid <- sorted[c(floor(n/2),floor(n/2)+1)]
    med <- sum(mid)/2
  } else {
    med <- sorted[ceiling(n/2)]
  }
  med
}

homemade_median(list1)
median(list1) # for comparison

您不需要测试均匀性,您只需使用长度的一半加一来创建一个序列,适当地使用 floorceiling:

x <- rnorm(100)
y <- rnorm(101)

my_median <- function(x)
{
mid <- seq(floor((length(x)+1)/2),ceiling((length(x)+1)/2))
mean(sort(x)[mid])
}

my_median(x)
[1] 0.1682606
median(x)
[1] 0.1682606
my_median(y)
[1] 0.2473015
median(y)
[1] 0.2473015

一个可以解决问题的简短函数:

my_median <- function(x){
   # Order Vector ascending
   x <- sort(x)
   # For even lenght average the value of the surrounding numbers
   if((length(x) %% 2) == 0){
    return((x[length(x)/2] + x[length(x)/2 + 1]) / 2)
   }
   # For uneven lenght just take the value thats right in the center
   else{
     return(x[(length(x)/2) + 0.5])
   }
}

检查是否returns 想要的结果:

my_median(list1) 
44.5
median(list1)
44.5
#
list2 <- c(1,4,5,90,18)
my_median(list2)
5
median(list2)
5