Search code examples
r

How do I retrieve a simple numeric value from a named numeric vector in R?


I am using R to calculate some basic statistic results. I am using the quantile() function,to calulate quantiles on a data frame column as follows.

> quantile(foobars[,1])
     0%     25%     50%     75%    100% 
 189000  194975  219500  239950 1000000 

I want to be able to individually access the calculated quantiles. However, I can't seem to find out how to do that. When I check the class of the returned result, it a 1 dimensional numeric.

I tried this:

> q <- quantile(foobars[,1])
> q[3]
   50% 
219500

Which seems to return a tuple (quantile level + number). I am only interested in the number (219500 in this case.

How may I access only the number into a simple (numeric) variable?


Solution

  • You are confusing the printed representation of the numeric value with the actual value. As far as R is concerned, q contains a named numeric vector:

    > dat <- rnorm(100)
    > q <- quantile(dat)
    > q
            0%        25%        50%        75%       100% 
    -2.2853903 -0.5327520 -0.1177865  0.5182007  2.4825565 
    > str(q)
     Named num [1:5] -2.285 -0.533 -0.118 0.518 2.483
     - attr(*, "names")= chr [1:5] "0%" "25%" "50%" "75%" ...
    

    All the "named" bit means is that the vector has an attached attribute "names" containing the (in this case) quantile labels. R prints these for a named vector as they are considered helpful to have in printed output if present. But, they in no way alter the fact that this is a numeric vector. You can use these in computations as if they didn't have the "names" attribute:

    > q[3] + 10
         50% 
    9.882214
    

    If the names bother you, the unname() function exists to remove them:

    > q2 <- unname(q)
    > q2
    [1] -2.2853903 -0.5327520 -0.1177865  0.5182007  2.4825565
    

    For completeness, I should probably add that you can extract the "names" using the names() function, which also has an assignment version ('names<-'()). So another way to remove the names from a vector is to assign NULL to the names:

    > q3 <- q
    > names(q3)
    [1] "0%"   "25%"  "50%"  "75%"  "100%"
    > names(q3) <- NULL
    > names(q3)
    NULL