Reputation: 845
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?
Upvotes: 0
Views: 67
Reputation: 4889
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)
}
Upvotes: 2