mizzlosis
mizzlosis

Reputation: 587

How to use column names starting with numbers in ggplot functions

I have a huge dataframe, whose variables/ column names start with a number such as `1_variable`. Now I am trying to create a function that can take these column names as arguments to then plot a few boxplots using ggplot. However I need the string but also need to to use its input with `` to use the arguments in ggplot. However I am not sure how to escape the character string such as "1_variable" to give ggplot an input that is `1_variable`.

small reproducible example:

dfx = data.frame(`1ev`=c(rep(1,5), rep(2,5)), `2ev`=sample(10:99, 10), 
             `3ev`=10:1, check.names = FALSE)

If I were to plot the figure manually, the input would look like this:

 dfx$`1ev` <- as.factor(dfx$`1ev`)
 ggplot(dfx, aes(x = `1ev`, y = `2ev`))+
   geom_boxplot()

the function I'd like to be able to run for the dataframe is this one:

plot_boxplot <- function(data, group, value){
    data = data[c(group, value)]
    data[,group] = as.factor(data[,group])
    plot <- ggplot(data, aes(x = group, y = value))+
    geom_boxplot() 
    return(plot)
}

1. Try

plot_boxplot(dfx, `1ev`, `2ev`)

which gives me an error saying Error in [.data.frame(data, c(group, value)) : object '1ev' not found

2. Try

entering the arguments with double quotes "" gives me unexpectedly this:

plot_boxplot(dfx, "1ev", "2ev")

unexpected output

3. Try I also tried to replace the double quotes of the string with gsub in the function

gsub('\"', '`', group)

but that does not change anything abut its output.

4. Try

finally, I also tried to make use of aes_string , but that just gives me the same errors.

plot_boxplot <- function(data, group, value){
   data = data[c(as.character(group), as.character(value))]
   data[,group] = as.factor(data[,group])
   plot <- ggplot(data, aes_string(x= group, y=value))+
     geom_boxplot() 
   return(plot)    
}

plot_boxplot(dfx, `1ev`, `2ev`)

plot_boxplot(dfx, "1ev", "2ev")

Ideally I would like to run the function to produce this output:

plot_boxplot(dfx, group = "1ev", value = "2ev")

expected output

[can be produced with this code manually]

ggplot(dfx, aes(x= `1ev`, y=`2ev`)) +
  geom_boxplot() 

Any help would be greatly appreciated.

Upvotes: 2

Views: 2566

Answers (1)

Nate
Nate

Reputation: 10671

One way to do this is a combination of aes_ and as.name():

plot_boxplot <- function(data, group, value){
    data = data[c(group, value)]
    data[,group] = as.factor(data[,group])

    plot <- ggplot(data, aes_(x= as.name(group), y=as.name(value))) +
      geom_boxplot()

    return(plot)
}

And passing in strings for group and value:

plot_boxplot(dfx, "1ev", "2ev")

enter image description here

It's not the same plot you show above, but it looks to align with the data.

Upvotes: 5

Related Questions