Search code examples
rsubsetmedian

Median : need numeric data


Why regular subsetting might not work? I wanted to calculate median from a data.table:

    > median(DT.UsersA3[,1])
Error in median.default(DT.UsersA3[, 1]) : need numeric data

it is numeric though:

> class(DT.UsersA3$Timedif)
[1] "numeric"

With iris data frame it works:

> median(iris[,3])
[1] 4.35

And lexical subsetting also works...

> median(DT.UsersA3$Timedif)
[1] 422.046

Solution

  • Here is the example with iris:

    library(data.table)
    Iris <- data.table(iris)
    median(Iris[,1])
    # Error in median.default(Iris[, 1]) : need numeric data
    Iris[,1] # is a data.table
    Iris[,Sepal.Length] # is a vector
    

    To use the number of the column you can follow the comment from Dason:

    Iris[[1]] # would return a vector 
    median(Iris[[1]]) # works