Reputation: 4762
Suppose I have a data frame
df <- data.frame(id = 1:2, vectors = I(list(1:15, 4:20)))
and I want to add a few columns with the quantiles of each vector, can I do this using one line of code with maybe do()
or some form of mutate()
?
Upvotes: 2
Views: 939
Reputation: 887098
One option is
library(dplyr)
df1 <- df %>%
rowwise() %>%
do(qnt= quantile(.$vectors))
bind_cols(df, as.data.frame(do.call(rbind, df1$qnt)))
# id vectors 0% 25% 50% 75% 100%
#1 1 1, 2, 3,.... 1 4.5 8 11.5 15
#2 2 4, 5, 6,.... 4 8.0 12 16.0 20
Or
bind_cols(df, df %>%
rowwise() %>%
do(qnt= as.data.frame(t(quantile(.$vectors))))%>%
lapply(., bind_rows) %>%
.$qnt)
Upvotes: 1