英文:
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 else
s there for all kinds of variables.
plot_hist_or_bar <- function(x) {
if(is.numeric(x)) {
hist(x)
} else if(is.factor(x)) {
barplot(table(x))
} else {
stop("Input variable must be numeric or a factor.")
}
}
Testing
x <- rnorm(100)
plot_hist_or_bar(x)
<!-- -->
y <- factor(rep(c("A", "B"), 50))
plot_hist_or_bar(y)
<!-- -->
<sup>Created on 2023-02-06 with reprex v2.0.2</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论