Hi everyone,
I came to this question in a similar fashion as my previous post on spaces in names with **ply, but this is slightly different because I can't get arrange to work where the column name to arrange by is stored in a variable regardless of spaces or not.
> df <- data.frame(x=c(3,2,1), "y z" = c(12,6,9), check.names = FALSE)
> r <- "x"
> s <- "y z"
Using arrange, I am trying to produce the following that works with order:
> df[order(df[[r]]), ]
x y z
3 1 9
2 2 6
1 3 12
> df[order(df[[s]]), ]
x y z
2 2 6
3 1 9
1 3 12
It is clear that arrange does work with when using backticks with the name directly:
> library(plyr)
> arrange(df, `x`)
x y z
1 1 9
2 2 6
3 3 12
> arrange(df, `y z`)
x y z
1 2 6
2 1 9
3 3 12
but not when stored in a variable (note, I threw in my solution to the previous post on creating a .. function that has been working great for **ply calls)
> arrange(df, r)
Error: Length of ordering vectors don't match data frame size
> arrange(df, .(r))
Error: Length of ordering vectors don't match data frame size
> `..` <- function(x){return(paste0("`", x, "`"))}
> arrange(df, ..(r))
Error: Length of ordering vectors don't match data frame size
Does anyone have any suggestions on how to use arrange where the column is a variable name? I feel like I am missing something obvious here, so I apologize in advance if that is the case.
Best wishes,
Doug