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.
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
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 level
s 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%"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With