直方图R - 以百分比显示数据

时间:2017-05-29 19:49:24

标签: r histogram

我有关于在火车事故中死亡的人及其年龄的数据。

例如:

file <- data.frame(
        Survived = sample(0:1, 100, replace=TRUE),
        Age = sample(0:100, 100, replace=TRUE))

我想在R中创建一个直方图,其中每个bin测量死亡人数占bin范围中包含的数据集总人数的百分比。

这是我到目前为止所做的:

hist(file[which(file$Survived==1),]$Age, freq=FALSE)

但这仅返回一个直方图,其值为整个数据集的百分比。像这样:Histogram of Sample Data

我需要一定比例的特定年龄组,以便如果0-10岁的所有人都死亡,直方图栏将在该年龄组中达到100%。

1 个答案:

答案 0 :(得分:2)

我不确定我是否理解您的数据,但可以使用barplot函数:

#example data    
AGE<-c(rep("<20",6),rep("20-40",6),rep("40-60",9))
set.seed(123)
SURVIVED<-sample(c(0,1), replace=TRUE, size=21)
df<-data.frame(AGE,SURVIVED)

#output of the data
df
     AGE SURVIVED
1    <20        0
2    <20        1
3    <20        0
4    <20        1
5    <20        1
6    <20        0
7  20-40        1
8  20-40        1
9  20-40        1
10 20-40        0
11 20-40        1
12 20-40        0
13 40-60        1
14 40-60        1
15 40-60        0
16 40-60        1
17 40-60        0
18 40-60        0
19 40-60        0
20 40-60        1
21 40-60        1

#the actual code
barplot(prop.table(table(df$SURVIVED,df$AGE), margin =2)[2,])

#and the proportions per group
> prop.table(table(df$SURVIVED,df$AGE), margin =2)

          <20     20-40     40-60
  0 0.5000000 0.3333333 0.4444444
  1 0.5000000 0.6666667 0.5555556

table会为您提供每个年龄组SURVIVED==1的频率,prop.table会为您提供百分比。

enter image description here

这接近你想要的吗?

相关问题