0

I'm trying to automate some graphing, without resorting to traditional loops. I'm having difficulty figuring out how to pass the elements of a row of a dataframe as the arguments of a function. The function looks like:

makeline  <- function(df, var, date, ylab="",xlab="", title="", nbershade=TRUE) {
p <- ggplot(df, aes_string(x=date, y=var)) 
p <- p  + geom_line()

# do some other magical things 
}

Lets say I have a dataframe with a row as follows:

row1 <- c("corn","Price","Date")

Since corn is a dataframe ggplot choked on it as a character. Then I used corn without the quotes and since it is a dataframe with column names "Price" and "Date", I thought this would work:

mapply(makeline,row1[1],row1[2],row1[3])

Anyhow, I'm fumbling trying to figure out efficiently use this new function without resulting to looping through lists. Any pointers appreciated.

tjbrooks
  • 81
  • 2
  • 12

2 Answers2

1

I'm not sure I would recommend this as a strategy, but you can use get to get the data.frame

makeline  <- function(df, var, date, ylab="",xlab="", title="", nbershade=TRUE) {
  df <- get(df)
  p <- ggplot(df, aes_string(x=date, y=var)) 
  p <- p  + geom_line()

# do some other magical things 
}

You may need to adjust the environment for get to work consistently, but it has inherits = TRUE which takes care of most things

data(mtcars)
data(diamonds)

Map(makeline, df = c('mtcars','diamonds'), var = c('cyl','x'), date = c('mpg','y'))
mnel
  • 110,110
  • 27
  • 254
  • 248
  • Thanks. This works. If I - as you do - pass the character vectors in directly, and use the `get` function for the df it works as I would like. I can even create and name the character vectors outside the `mapply`, however I seem not to be able to pass the vectors by referencing the colnames if the character vectors are bound together in a data frame. For example: – tjbrooks Mar 12 '13 at 14:38
  • @tjbrooks, It looks like you have a typo in your column names, `data2$x3` should be `data2$X3`. If you are using `mapply`, you will need to have `SIMPLIFY = FALSE`, that is why I used `Map`, which is a simple wrapper for `mapply(..., SIMPLIFY = FALSE)` – mnel Mar 12 '13 at 22:15
0

try this

mapply(makeline,get(row1[,1]),row1[,2],row1[,3])
CHP
  • 16,581
  • 4
  • 35
  • 56