如何构建一个函数,根据变量来构建直方图或柱状图

huangapple go评论50阅读模式
英文:

How to construct a function that will construct a histogram or a bar chart depending the variable

问题

我如何构建一个函数(在基本R中),它将接收一个变量作为输入参数,并根据该变量是数量型还是分类型来构建直方图或柱状图?我已经尝试过搜索,但解决方案必须在不下载额外包的情况下找到。

英文:

How can I construct a function (in base R)which will receive as an input parameter a variable, and will construct a histogram or a bar chart depending on whether it will be a quantitative or categorical variable?

I have tried googling but the solution has to be found witout an extra package downloaded

答案1

得分: 2

函数

假设您正在使用numeric变量或factor。但您可以继续为所有类型的变量添加if else

plot_hist_or_bar <- function(x) {
  if(is.numeric(x)) {
    hist(x)
  } else if(is.factor(x)) {
    barplot(table(x))
  } else {
    stop("输入变量必须是numeric或factor类型。")
  }
}

测试

x <- rnorm(100)
plot_hist_or_bar(x)

如何构建一个函数,根据变量来构建直方图或柱状图

y <- factor(rep(c("A", "B"), 50))
plot_hist_or_bar(y)

如何构建一个函数,根据变量来构建直方图或柱状图

创建于2023-02-06,使用 reprex v2.0.2

英文:

Function

Assuming you are working with numeric variables or factor. But you can keep putting if elses there for all kinds of variables.


plot_hist_or_bar &lt;- function(x) {
  if(is.numeric(x)) {
    hist(x)
  } else if(is.factor(x)) {
    barplot(table(x))
  } else {
    stop(&quot;Input variable must be numeric or a factor.&quot;)
  }
}

Testing


x &lt;- rnorm(100)
plot_hist_or_bar(x)

如何构建一个函数,根据变量来构建直方图或柱状图<!-- -->


y &lt;- factor(rep(c(&quot;A&quot;, &quot;B&quot;), 50))
plot_hist_or_bar(y)

如何构建一个函数,根据变量来构建直方图或柱状图<!-- -->

<sup>Created on 2023-02-06 with reprex v2.0.2</sup>

huangapple
  • 本文由 发表于 2023年2月7日 01:41:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75364759.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定