broccoli
broccoli

Reputation: 4846

Output of quantile to a data frame

This is a fairly basic question, but haven't seen a good answer on various forums. Say I've a simple vector

x = runif(10,1,4)
> x
[1] 3.292108 1.388526 2.774949 3.005725 3.904919 1.322561 2.660862 1.400743
[9] 2.252095 3.567267
> 

Next I compute some quantiles,

> z = quantile(x,c(0.1,0.8))
> z
 10%      80% 
1.381929 3.347140 
> 

I need this output as a data frame. So I tried the following

> y = data.frame(id = names(z),values=z)
> y
 id   values
10% 10% 1.381929
80% 80% 3.347140

I see that the "%" column is repeated. Also when I try

> y$id[1]
[1] 10%
Levels: 10% 80%

whereas I'm expecting it to be either just "10%" or 0.1 Any help appreciated.

Upvotes: 5

Views: 13579

Answers (2)

GSee
GSee

Reputation: 49830

You get the names twice because you're giving data.frame the names twice -- first as a vector, then as part of the named vector. You're getting levels because by default, stringsAsFactors is TRUE.

set.seed(1)
x <- runif(10,1,4)
z <- quantile(x, c(0.1, 0.8))
y <- data.frame(id=names(z), values=unname(z), stringsAsFactors=FALSE)
y
#   id   values
#1 10% 1.563077
#2 80% 3.701060

y$id[1]
#[1] "10%"

Upvotes: 6

mnel
mnel

Reputation: 115485

The names are just the probabilities so

y <- data.frame(id = c(0.1, 0.8), values = z) 

Would work.

So would wrapping it in a function that returns a data.frame

quantile_df <- function(x, probs, na.rm =F, names = F, type = 7, ...){
  z <- quantile(x, probs, na.rm, names, type)
  return(data.frame(id = probs, values = z))
}

quantile_df(x, probs = c(0.1, 0.8))
##    id   values
## 1 0.1 1.343383
## 2 0.8 2.639341

Upvotes: 7

Related Questions