R语言 如何创建返回给定数据框直方图的函数?

k2fxgqgv  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(155)

I need to create a function called histagram, the function receives 3 arguments: data frame, column name, and color number.
if all the arguments meet the criteria (valid data frame, color number an integer, and column name input must be character and the column must be of type numeric, the function returns a plot of histogram of the chosen column with the chosen color.
Also we need to change the "x - axis" so it will represent the column name input.
my script:

histagram = function(dataframe, columnName, colorNumber) {
    if (!is.data.frame(dataframe)){
    print("Please enter a Data frame structure")
  } else if(!is.integer(as.integer(colorNumber))){
    print("Enter a char columne name")    
  } else if(!is.character(columnName)){
    print("Color must be a integer")  
  } else {
    return(hist(dataframe$as.numeric(columnName), xlab = "columnName", col = as.integer(colorNumber)))
  }
}

I tested the function to see if it worked:

histagram(dataframe = airdf, colorNumber = 7, columnName = "Temp")

I used the airquality data frame, which is a built-in data frame in R. airdf = airquality.
I'm getting an error message -

Error in dataframe$as.numeric(columnName) : attempt to apply non-function
Called from: hist(dataframe$as.numeric(columnName), xlab = "columnName", col = as.integer(colorNumber))

What needs to be changed in my code for it to work?
Many thanks!

slwdgvem

slwdgvem1#

除了Martin Gal的注解之外,您还应该删除xlab参数下columnName周围的引号,并考虑在直方图标题中添加一些内容。如果您不指定直方图标题,它只显示“Histogram of as.numeric(dataframe[,columnName])",这有点笨拙。

data(airquality)
airdf <- airquality

histagram <- function(dataframe, columnName, colorNumber) {
  if (!is.data.frame(dataframe)){
    print("Please enter a Data frame structure")
  } else if(!is.integer(as.integer(colorNumber))){
    print("Enter a char columne name")    
  } else if(!is.character(columnName)){
    print("Color must be a integer")  
  } else {
    return(hist(as.numeric(dataframe[, columnName]), # <- from Martin Gal
                main = paste("Histogram of", columnName), # <- dynamic title 
                xlab = columnName, # <- remove quotes here
                col = as.integer(colorNumber)))
  }
} 

histagram(dataframe = airdf, colorNumber = 7, columnName = "Temp")

相关问题