Home > Mobile >  Find and visualize median of a set of numbers when one value is unknown in R
Find and visualize median of a set of numbers when one value is unknown in R

Time:12-21

I have a set of numbers:

X <- c(-1,5,2,9,6,-2,-9,0,4,x)

x is unknown.

I need to get an equation for median which depend on x. And then plot a line chart with 'x' as x-axis and 'Median' as y-axis.

x = seq(-10,10,1)
Median <- "the equation"
plot(x,Median,type="l")

CodePudding user response:

Let's consider X, the vector X (without x). X has an odd number of elements (9) and the median is the central value: sort(X)[5]. In this case, 2. However, as a number is added to X, the number of elements will be even and the median will become the mean of the two central numbers. The following Median function can estimate the median of c(x, X) depending on x being above or below the number with rank 4 (0) or 6 (4) in X.

X <- c(-1,5,2,9,6,-2,-9,0,4)
sort(X)[4:6]
#> [1] 0 2 4
Median <- function(x) {
    if (x <= 0) 1 else if (x >= 4) 3 else .5 *(x   2)
}

curve(Vectorize(Median)(x), -10, 10)

Median

  • Related