0

I have a data with 8 variables (x1,y1,x2,y2,x3,y3,x4,y4), and i should do a function that generate a 4 plots x1vsy1, x2vsy2, x3vsy3 and x4vsy4.

So i was trying to do that one by one, doing a new data with the variables and after generate de plot.

minidata<-select(alldata,x1,y1)
ggplot(minidata,aes(x1,y1))+geom_point()+ggtitle("m VS n")

This works, but when i try to put that in the function

graph<-function(m,n){
 minidata<-select(alldata,m,n)
  ggplot(minidata,aes(x=m,y=n))+geom_point()+ggtitle("m VS n")
}
graph(y1,x1)

This doesnt work say "Error in FUN(X[[i]], ...) : object 'y1' not found" what i could do to generate a function that creates the 4 plots?

fran
  • 1

1 Answers1

0

There are a number of ways doing this. One approach is:

minidata <- data.frame( x1 = 1:20,
                        y1 = rnorm(20), 
                        x2 = 1:20,
                        y2 = runif(20))


myGraph <- function( df, x, y ){

  mdf <- df[ ,c(x,y)]
  names(mdf) <- c("x","y")
  ggplot(mdf,aes(x=x,y=y))+geom_point() + ggtitle(paste(y,"~",x)) + labs (x =x, y = y)
}

# call function by passing names of the column using names() function
myGraph (minidata, names(minidata)[1], names(minidata)[2])

# or simply giving a name
myGraph (minidata, "x2", "y2")

enter image description here

Katia
  • 3,784
  • 1
  • 14
  • 27