如何通过R中的分类变量对定量变量进行分组(以制作直方图)

时间:2017-03-18 22:49:44

标签: r rstudio-server

我试图获得定量变量的方法,然后绘制这个量变量的方法BY星期几(分类)

尝试重组数据等,但现在可以利用。

非常简单,但让我难过。谢谢!

2 个答案:

答案 0 :(得分:1)

一般例子:白天的平均收入

library(data.table)
library(ggplot2)

setDT(data)

# get average income by day
  temp <- data[, .(mean_income= mean(income, na.rm=T)), by = day]

# plot
  ggplot(data=temp) + 
    geom_bar( aes(x=day, y= mean_income) , stat = "identity") +
    labs(x="day of the week", y="average income")

答案 1 :(得分:0)

怎么样:

library(dplyr)
x <- data.frame(day = rep(c("monday", "tuesday",  "wednesday") ,3), val = runif(9))

x2 <- x %>%
group_by(day) %>% 
summarise(mean = mean(val))

barplot(x2$mean, names.arg = x2$day)

enter image description here