0

I want to write an R function that reads in a file m, and plots a boxplot using ggplots2.

This is function:

stringplotter = function(m, n) {
library(ggplot2)
require(scales)
data<-as.data.frame(read.table(file=m, header=T, dec=".", sep="\t"))
ggplot(data, aes(x=string, y=n)) + geom_boxplot() + geom_point() + scale_y_continuous(labels=comma)
}

An example file test:

C   string
97  ccc
95.2    ccc
88.6    nnn
0.5 aaa
86.4    nnn
0   ccc
85  nnn
73.9    nnn
87.9    ccc
71.7    nnn
94  aaa
76.6    ccc
44.4    ccc
92  aaa
91.2    ccc

When I then call the function

stringplotter("test", C)

I get the error

Fehler: Column `y` must be a 1d atomic vector or a list
Call `rlang::last_error()` to see a backtrace

When I call the commands inside the function directly, everything works as expected. Where is my error?

1

1 Answer 1

2

The problem is that when you write y = n, ggplot2 doesn't know how to evaluate value of n. You can use rlang to quote the input and it will be evaluated within the entered dataframe-

stringplotter <- function(m, n) {
  library(ggplot2)
  require(scales)
  data <-
    as.data.frame(read.table(
      file = m,
      header = T,
      dec = ".",
      sep = "\t"
    ))
  ggplot(data, aes(x = string, y = !!rlang::enquo(n))) + 
    geom_boxplot() + 
    geom_point() + 
    scale_y_continuous(labels = comma)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.