r - ggplot: shaping data for a scatterplot -
r - ggplot: shaping data for a scatterplot -
i have info frame next (imagine multiple markets, 1 market: 2 variables):
market variables median lower.limit upper.limit market_1 var_1 2.78 2.71 2.72 market_1 var_2 3.21 2.96 3.44 market_2 var_1 2.95 2.79 3.11 market_2 var_2 2.11 1.91 2.30
i scatter plot whiskers of info (var_1 vs var_2), i'm having problem understanding how reshape data. think info frame needs go long wide form, i'm not sure lower/upper limits in transformation. columns be:
market var_1 var_1_lower.limit var_1_upper.limit var_2_median var_2_lower.limit var_2.upper.limit
or there way subset info straight ggplot?
if want reshape info wide
form, can utilize reshape
base r
reshape(df, idvar="market", timevar='variables', direction='wide') # market median.var_1 lower.limit.var_1 upper.limit.var_1 median.var_2 #1 market_1 2.78 2.71 2.72 3.21 #3 market_2 2.95 2.79 3.11 2.11 # lower.limit.var_2 upper.limit.var_2 #1 2.96 3.44 #3 1.91 2.30
or using dplyr/tidyr
library(dplyr) library(tidyr) df %>% gather(var, val, median:upper.limit) %>% unite(varn,variables, var, sep="_") %>% spread(varn, val) # market var_1_lower.limit var_1_median var_1_upper.limit var_2_lower.limit #1 market_1 2.71 2.78 2.72 2.96 #2 market_2 2.79 2.95 3.11 1.91 # var_2_median var_2_upper.limit #1 3.21 3.44 #2 2.11 2.30
or using dcast/melt
reshape2
library(reshape2) dcast(melt(df, id=c("market", "variables")), market~..., value.var='value') # market var_1_median var_1_lower.limit var_1_upper.limit var_2_median #1 market_1 2.78 2.71 2.72 3.21 #2 market_2 2.95 2.79 3.11 2.11 # var_2_lower.limit var_2_upper.limit #1 2.96 3.44 #2 1.91 2.30
data df <- structure(list(market = c("market_1", "market_1", "market_2", "market_2"), variables = c("var_1", "var_2", "var_1", "var_2" ), median = c(2.78, 3.21, 2.95, 2.11), lower.limit = c(2.71, 2.96, 2.79, 1.91), upper.limit = c(2.72, 3.44, 3.11, 2.3)), .names = c("market", "variables", "median", "lower.limit", "upper.limit"), class = "data.frame", row.names = c(na, -4l))
r ggplot2 shape
Comments
Post a Comment