ggplot2 - How to call functions using the character string of the function name in R while using the ggplot package? -


i've been trying write r code reads data excel file , plot different graph charts (like: bar, line, point or pie) based on user input, using ggplot package.

for this, using 3-4 different functions:

1) function bar plotting:

bar <- function() {   plot <- ggplot (data= df, aes(x= dates, y= values))   barplot <- plot + geom_bar(stat="identity", fill="red", width=1)   print(barplot) } 

2)similarly, line plot :

line <- function() { plot <- ggplot (data= df, aes(x= dates, y= values)) lineplot <- plot + geom_line(aes(group=1), colour="blue", size=0.5) print(lineplot) } 

3) main function, declares libraries , reading excel workbook data frame.

in main function trying call different plot functions using "if else" follows:

    main <- function() {  library(xlconnect) library(ggplot2)  wk <- loadworkbook("d:\\....xlsx") dataframe = readworksheet (wk, sheet="sheet1", header=true) df <- data.frame(dates = dataframe[,1],                  values =dataframe[,2])      name <- scan(what = " ")     if (name == "bar")     { bar() }      else if (name == "line")         { line() } } 

but throws error: " ggplot2 doesn't know how deal data of class function".

simplified version of data:

dates values jan   46 feb   54 mar   32 

how can modify code accommodate requirement of being able plot different graphs per user input?

your problem related variable scope: dataframe defined within main() available within main(). won't visible other functions such bar() or line(), even if called within main().

the preferred solution pass data function needs explicitly. so, define functions eg:

bar <- function(df) {   plot <- ggplot (data= df, aes(x= dates, y= values))   barplot <- plot + geom_bar(stat="identity", fill="red", width=1)   print(barplot) } 

and call main() so:

main <- function() {   library(ggplot2)   df <- data.frame(dates = c("jan", "feb", "mar"),                    values =c(46, 54, 52))   name <- scan(what = " ")   if (name == "bar")   { bar(df) } } 

there other ways deal problem, i'll mention completeness, though aren't nice 1 above. first, nest function definitions, eg:

main <- function(){     bar <- function(){         ...     }     ...     bar() } 

this works because functions defined inside of other functions have access variables defined within function.

finally, functions have access global varaibles, can either define variables outside of main() or define them globals using <<- operator.


Comments

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -