Search code examples
rbar-chartlattice

Is there a way to dynamically build the x axis variables


Set up a date frame

 a <- c(5, 10, 15, 20)
 b <- c(50, 100, 150, 200)
 c <- c(150, 200, 250, 300)
 d <- c("A", "B", "C", "D")
 df <- data.frame(a, b, c, d)
 names(df) <- c("XData1", "XData2", "XData3", "YData")
 df
  XData1 XData2 XData3 YData
1      5     50    150     A
2     10    100    200     B
3     15    150    250     C
4     20    200    300     D

Using the lattice library, create a barchart

barchart(YData ~ XData1, data=df)

Create a second, more complicated barchart using

barchart(YData ~ XData1+XData2+XData3, data=df, stack=TRUE)

Now the question is, how to create the barchart using a function.

Create the first chart by calling a function like this:

CreateBarChart(df, c('XData1'), c('YData')) 

and the second chart by calling a function like this:

CreateBarChart(df, c('XData1','XData2','XData3'), c('YData'))

What do I do in the function to create the barchart? That is what I don't understand. I need to dynamically build the XData1+XData2+XData3 string in a variable and use it in the barchart.

ORIGINAL QUESTION

I have a set of data that includes a varying number of columns to include in the graph. The simple case, the command looks like this:

barchart(my_data[, ycol] ~ my_data[, xcol])

In the more complicated case, the command looks like this:

barchart(my_data[, ycol] ~ my_data[, xcol][[1]]+my_data[, xcol][[2]]+my_data[, xcol][[3]])

The issue is that the number of xcol variables can vary.

I want to build the my_data[, xcol][[1]]+my_data[, xcol][[2]]+my_data[, xcol][[3]] part of the command dynamically based on the length(xcol).

Any help would be appreciated.


Solution

  • You build up the string and convert into a formula. barchart can then take that and the data:

    CreateBarChart=function(Data,YVAR,XVAR){
    FORMULA = as.formula(paste(YVAR,"~",paste(XVAR,collapse="+")))
    barchart(FORMULA,data=Data)
    } 
    

    We test:

    CreateBarChart(df,'YData','XData1')
    

    enter image description here

    CreateBarChart(df,'YData',c('XData1','XData2'))
    

    enter image description here