R - 以变量作为 X 轴名称的绘图函数

R - Plot Function with Variable as X-axis Name

我有一个简单的函数可以创建传递变量的直方图,但我希望该函数将直方图命名为 "Histogram of X",其中 X 是变量的名称。

我还希望它也将 X 轴命名为变量的名称。

我该怎么做?

这是目前的功能,但没有给出我想要的正确标签:

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

谢谢

当您需要调整文本时。找到这个 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)

已更新为使用 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) ]