1

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)  
aynber
  • 22,380
  • 8
  • 50
  • 63
Bertrand G
  • 37
  • 6

2 Answers2

1

I'd use lappy such as:

myFUN<-function(x){  

  themean<-mean(df[[x]])  
  thevar<-var(df[[x]])  

  Name<-x  
  thetitle <- paste('Variable: ', Name, '')  
  hist(df[[x]],main=thetitle, xlab = Name)  

  return(list(themean, thevar))  
}  

lapply(names(df), myFUN)  
Andrew Taylor
  • 3,438
  • 1
  • 26
  • 47
1

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.

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66