I'm looking for a way to create multiple columns based on the quantile() function output. I actually want the quantile of each rows containing womens and mens value.
Example for line 1 :
I want quantile(c(4.6, 5.8))
Which give :
0% 25% 50% 75% 100%
4.6 4.9 5.2 5.5 5.8
Here is a sample of data and the output I want :
data :
code womens mens
1: 01 4.6 5.8
2: 02 5.0 4.6
3: 03 4.1 5.3
4: 04 5.2 3.0
5: 05 4.6 5.4
6: 06 2.3 3.4
what I want :
code womens mens 0% 25% 50% 75% 100%
1: 01 4.6 5.8 4.6 4.9 5.2 5.5 5.8
2: 02 5.0 4.6 4.6 4.7 4.8 4.9 5.0
3: 03 4.1 5.3 4.1 4.4 4.7 5.0 5.3
4: 04 5.2 3.0 3.0 3.5 4.1 4.6 5.2
5: 05 4.6 5.4 4.6 4.8 5.0 5.2 5.4
6: 06 2.3 3.4 2.3 2.6 2.8 3.1 3.4
I already tried with lapply() and some for loop without results. The result I had was always the same 4.6 4.9 5.2 5.5 5.8 for every rows.
Thanks everyone
cbind(d, do.call(rbind, lapply(1:NROW(d), function(i){
quantile(d[i, c("womens", "mens")])
})))
# code womens mens 0% 25% 50% 75% 100%
#1: 1 4.6 5.8 4.6 4.900 5.20 5.500 5.8
#2: 2 5.0 4.6 4.6 4.700 4.80 4.900 5.0
#3: 3 4.1 5.3 4.1 4.400 4.70 5.000 5.3
#4: 4 5.2 3.0 3.0 3.550 4.10 4.650 5.2
#5: 5 4.6 5.4 4.6 4.800 5.00 5.200 5.4
#6: 6 2.3 3.4 2.3 2.575 2.85 3.125 3.4
DATA
d = structure(list(code = 1:6,
womens = c(4.6, 5, 4.1, 5.2, 4.6, 2.3),
mens = c(5.8, 4.6, 5.3, 3, 5.4, 3.4)),
class = "data.frame",
row.names = c("1:", "2:", "3:", "4:", "5:", "6:"))
If it is a data.table, one option in base R, would be to convert to data.frame (setDF), then loop through the rows with apply (MARGIN = 1), get the quantiles and assign new columns
library(data.table)
setDF(df1)
df1[c("0%", "25%", "50%", "75%", "100%")] <- t(apply(df1[, 2:3], 1,
quantile, na.rm = TRUE))
df1 <- structure(list(code = 1:6, womens = c(4.6, 5, 4.1, 5.2, 4.6,
2.3), mens = c(5.8, 4.6, 5.3, 3, 5.4, 3.4)), class = c("data.table",
"data.frame"), row.names = c(NA, -6L))
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