I am trying to compute observed, minimum and maximum values by group in order to plot with ggplot. I was able to do that in the following way:
library(tidyverse)
df <- cbind.data.frame("V1"=rnorm(100,10,2),
"V1_std"=rgamma(100,2),
"V2"=rnorm(100,10,2),
"V2_std"=rgamma(100,2))
df_obs <- df %>%
mutate("id"=1:nrow(.)) %>%
select(-c(V1_std,V2_std)) %>%
gather(...=1:2)
df_min <- df %>% mutate("V1_min"= V1 - V1_std) %>%
mutate("V2_min"= V2 - V2_std) %>%
select(V1_min,V2_min) %>%
gather(...=1:2)
df_max <- df %>% mutate("V1_max"= V1 + V1_std) %>%
mutate("V2_max"= V2 + V2_std) %>%
select(V1_max,V2_max) %>%
gather(...=1:2)
df_final <- cbind.data.frame(df_obs,'min'=df_min$value,'max'=df_max$value)
which gives me:
key value min max
1 V1 11.411261 7.2531585 15.569364
2 V1 10.804986 10.3518400 11.258132
3 V1 9.809049 8.5992110 11.018887
4 V1 11.225030 10.3028566 12.147204
5 V1 10.532991 10.2911703 10.774812
6 V1 9.993123 8.8835294 11.102717
7 V1 6.891480 4.3241776 9.458782
8 V1 12.492458 11.6869964 13.297920
9 V1 8.986359 5.0335530 12.939165
10 V1 8.667382 8.3316045 9.003160
Is there a simpler way to do that, using a single pipe?
Thanks