Search code examples
rdataframegraphapplyr-colnames

Getting dataframe column names with apply for graph title in R


I run the apply function on a dataframe's columns and perform several operations including plotting some graphs. I want to get the column names to use them as title of each graph. I found a post that uses lapply but I don't think I can use it since I need apply.

var1<-rnorm(100)
var2<-rnorm(100)
var3<-rnorm(100)  
df<-data.frame(var1,var2, var3)  
colnames(df)<-c("var1", "var2", "var3")  

myFUN<-function(x){  

  themean<-mean(x)  
  thevar<-var(x)  

  Name<-colnames(x)  
  thetitle <- paste('Variable: ', Name, '')  
  hist(x,main=thetitle)  

return(list(themean, thevar))  
}  

apply(df,2,myFUN)  

Solution

  • You can use mapply, the multivariate version of sapply. But you would need to rewrite the function to accept two arguments.

    myFUN2 <- function(x, Name){ 
    
      themean <- mean(x)  
      thevar <- var(x)  
    
      thetitle <- paste('Variable: ', Name, '')  
      hist(x, main = thetitle)  
    
      return(list(themean, thevar))  
    }  
    
    mapply(myFUN2, df, names(df))
    mapply(myFUN2, df, names(df), SIMPLIFY = FALSE)
    

    The first call simplifies the output to a matrix. The second does not, it returns a list.