我怎样才能开始这个 ggplot 问题?

How can I make a start on this ggplot question?

Write a function chartCol(df, colN), where:

  • df: one selected data frame (e.g. mpg, diamonds,or msleep)
  • colN: one selected column’s name (this should be a string, e.g. “displ”)

This function will return a plot (histogram/bar chart) based on the data type of the selected column. If it’s a continuous variable, it will show a histogram. If it’s a categorical variable, it will show a bar chart.

Hint: use aes_string to deal with string names when mapping.

我正在使用以下功能:

chartCol <- function(df,colN) {
  ggplot(df) + geom_bar(aes_string(colN))
  
}

但是,这只是 returns 条形图,当我在此函数中编写该代码时无法获得直方图。

我会让你的老师知道 aes_string 已被软弃用,最好这样做:

library(ggplot2)

chartCol <- function(df, colN) {
  ggplot(df, aes(x = !!ensym(colN))) +
  if(!is.numeric(df[colN])) geom_bar() else geom_histogram()
}

chartCol(diamonds, "carat")

chartCol(diamonds, "cut")

reprex package (v0.3.0)

于 2020-11-12 创建