Minimal reproducible example:
I have a dataframe df
with 3 columns, x, y,
and z
. I want to plot x
and y
by melting the first two columns of df
and passing the melted dataframe to ggplot
. I want to scale x
by 10 to plot it on a secondary axis. Currently I do the following:
df <- data. Frame(Date = seq(as.Date("2000/1/1"), by = "month", length. Out = 6),
x = rep(c(0,1), 3),
y = runif(6, 0,10 ),
z = 1:6)
df_tmp <- df[, c("Date", "x", "y")]
df_tmp[["x"]] <- df_tmp[["x"]] * 10
df_melt <- df_tmp |>
reshape2::melt(id.vars = "Date",
variable.name = "Variable")
This works but seems clumsy – I really don’t want to create the intermediate dataframe df_tmp
. How can I rewrite this using the Base R (4.3.3) pipe so that I go from df
to df_melt
with x
scaled as I want but without modifying df
?
I’m looking for something that looks like:
df_melt <- df[, c("Date", "x", "y")] |>
???[["x"]] * 10 |>
reshape2::melt(id.vars = "Date",
variable.name = "Variable")
Many thanks in advance for your help
Thomas Philips