Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using dataframe column names as chart label in Apply

Tags:

r

lattice

I want to create a series of x-y scatter charts, where y is always the same variable and x are the variables I want to check if they are correlated with. As an example lets use the mtcars dataset.

I am relatively new to R but getting better.

The code below works, the list charts contains all the charts, except that the X axis shows as "x", and I want it to be the name of the variable. I tried numerous combinations of xlab= and I do not seem to get it

if I use names(data) I see the names I want to use. I guess I want to reference the first of names(data) the first iteration of apply, the second the second time, etc. How can I do that?

Th next step would be to print them in a lattice together, I assume an lapply or sapply will do the trick with the print function - I appreciate idea for this too, just pointers I do not need a solution.

load(mtcars)
   mypanel <- function(x,y,...) {
   panel.xyplot(x,data[,y],...)
   panel.grid(x=-1,y=-1)
   panel.lmline(x,y,col="red",lwd=1,lty=1)
   } 
   data <- mtcars[,2:11]
   charts <- apply(data,2,function(x) xyplot (mtcars[,1] ~ x, panel=mypanel,ylab="MPG")) 

This all started because I was not able to use the panel function to cycle.

like image 909
user1617979 Avatar asked Dec 06 '25 06:12

user1617979


1 Answers

I did not find that this code "worked". Modified it to do so:

mypanel <- function(x,y,...) {
   panel.xyplot(x, y, ...)
   panel.grid(x=-1, y=-1)
   panel.lmline(x,y,col="red",lwd=1,lty=1)
   } 
data <- mtcars[,2:11]
charts <- lapply(names(data), function(x) { xyplot (mtcars[,1] ~ mtcars[,x], 
                                               panel=mypanel,ylab="MPG", xlab=x)})

Needed to remove the 'data[,y]' from the panel function and pass names instead of column vectors so there was something to use for a x-label.

like image 67
IRTFM Avatar answered Dec 07 '25 20:12

IRTFM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!