【发布时间】:2021-07-22 10:28:32
【问题描述】:
我正在使用 R 编程语言。我为此示例创建了以下数据集:
var_1 <- rnorm(1000,10,10)
var_2 <- rnorm(1000, 5, 5)
var_3 <- rnorm(1000, 6,18)
favorite_food <- c("pizza","ice cream", "sushi", "carrots", "onions", "broccoli", "spinach", "artichoke", "lima beans", "asparagus", "eggplant", "lettuce", "cucumbers")
favorite_food <- sample(favorite_food, 1000, replace=TRUE, prob=c(0.5, 0.45, 0.04, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001))
response <- c("a","b")
response <- sample(response, 1000, replace=TRUE, prob=c(0.3, 0.7))
data = data.frame( var_1, var_2, var_3, favorite_food, response)
data$favorite_food = as.factor(data$favorite_food)
data$response = as.factor(data$response)
从这里开始,我想为这个数据集中的两个分类变量制作直方图,并将它们放在同一页面上:
#make histograms and put them on the same page (note: I don't know why the "par(mfrow = c(1,2))" statement is not working)
par(mfrow = c(1,2))
histogram(data$response, main = "response"))
histogram(data$favorite_food, main = "favorite food"))
我的问题:是否可以为给定数据集中的所有分类变量自动生成直方图(无需手动为每个变量编写“histogram()”语句)并将它们打印在同一页面上?使用“ggplot2”库来解决这个问题会更好吗?
我可以为数据集中的每个单独的分类变量手动编写“histogram()”语句,但我正在寻找一种更快的方法来做到这一点。是否可以使用“for 循环”来做到这一点?
谢谢
【问题讨论】:
-
注意这段代码的重现性不太好,因为你没有说你使用哪个包来调用
histogram,而且这些调用结束时似乎有一些多余的括号 -
[正如后续问题所暗示的,我认为 OP 使用的是
hist,但在这里写了histogram。]
标签: r loops ggplot2 data-visualization histogram