0

I have a simple function that will create a histogram of the passed variable, but I want for the function to name the histogram plot "Histogram of X" where X is the name of the variable.

I also want it to name the X-Axis the name of the variable as well.

How can I do this?

Here is the function currently, but not giving the correct labels I want:

plot.histogram <- function (x){
  hist(x, main = "Histogram of x", xlab = "x")
}

Thanks

David Robinson
  • 77,383
  • 16
  • 167
  • 187
Nate Thompson
  • 625
  • 1
  • 7
  • 22
  • 1
    At the moment you specify `main = "Histogram of x"` and `xlab = "x"` which means the histogram will always be labelled with those exact phrases. Are you aware that `hist(x)` alone appears to give the output you are asking for? – ping Mar 21 '15 at 16:15
  • Yes, I was aware that it would give me that output. What I was really wanting was how to label things in a function with the name of the variables passed. Its not that I necessarily want to use this function, I just want to learn how to assign labels of things based on the names of the variable passed in a function. – Nate Thompson Mar 21 '15 at 16:22

1 Answers1

0

For when you need to adjust the text. Found this SO post: Name of Variable in R

sweet = rnorm(100)

plot.histogram <- function (x){

    hist(x, main = paste("Awesome Histogram of",substitute(x)), xlab = paste(substitute(x)))
}

plot.histogram(sweet)

Updated to use a data.table

x = data.table( 'first'=rnorm(100),'second'=rnorm(100),'third'=rnorm(100))
plot.histogram <- function (x){
    if( is.null(names(x) ) ){
        mname = substitute(x)  
        hist(x, main = paste("Histogram of", mname ), xlab = paste( mname ))
    }else{
        mname = names(x)
        hist(x[[mname]], main = paste("Histogram of", mname ), xlab = paste( mname ))
    }
}
x[ , plot.histogram(.SD), .SDcols=c(1) ]
Community
  • 1
  • 1
Phillip Stich
  • 461
  • 4
  • 5
  • One quick follow-up, if I try to use this function as part of an apply() statement, it doesnt keep the names. Any advice? apply(df,2,plot.histogram) . It renames each newX[,1] instead of putting the correct labels – Nate Thompson Mar 21 '15 at 17:02
  • @nate-thompson Are you looking to apply the plot.histogram function over all columns of the data.frame? The hist function won't work for non-numeric columns – Phillip Stich Mar 21 '15 at 23:59
  • Correct, this is what I was wanting to do. My entire dataset has numeric columns, and it gave me the histogram output for each column, but the Title of each graph and the labels were the exact same "Histogram of newX[,1] – Nate Thompson Mar 23 '15 at 13:38
  • Sorry for the _really_ late reply on this. Instead of using the apply function just use a simple for loop. `for(i in 1:length(x)){ x[ , plot.histogram(.SD), .SDcols=c(i) ] } ` – Phillip Stich Mar 17 '16 at 05:10