Reputation: 1355
I have variables in dataframe and I am trying to build a function that allows me to plot a variable in a data without redudantly writing, data$variablename
.
plt=function(x){
plot(data$date,as.name(paste("data$",x,sep="")),type="l",xlab="Population",ylab="Time")
}
R keeps thinking that my y-variable is a name rather than a variable. How do I tell it that the y-axis input in the function plot
is a name rather than the actual variable?
Upvotes: 0
Views: 116
Reputation: 193507
I would try something like the following (two options provided--the uncommented one would be my preferred approach):
plt <- function(x, data = mydf) {
x <- deparse(substitute(x))
# with(data, plot(date, get(x), type = "l", xlab = "Population", ylab = "Time"))
plot(data[, "date"], data[, x], type = "l", xlab = "Population", ylab = "Time")
}
When using data[, x]
, x
needs to be a character vector, hence the use of deparse(substitute(x))
in the first line of the function. Thus, you would enter the y column unquoted. I've also added a "data
" argument to let you specify which dataset you are dealing with.
Try the function out with this:
set.seed(1)
mydf <- data.frame(date = 1:100, A = rnorm(100), B = rnorm(100), C = rnorm(100))
plt(A)
plt(B)
plt(C)
Upvotes: 2