R: apply/ lapply: 如果列中的所有条目都是 1,如何创建条形图?

R: apply/ lapply: How to Create a bar chart if all entries in on column are 1's?

想象一下,您有以下数据集:

df<-data.frame(read.table(header = TRUE, text = "
ID  Wine    Beer    Water   Age Gender
1   0   1   0   20  Male
2   1   0   1   38  Female
3   0   0   1   32  Female
4   1   0   1   30  Male
5   1   1   1   30  Male
6   1   1   1   26  Female
7   0   1   1   36  Female
8   0   1   1   29  Male
9   0   1   1   33  Female
10  0   1   1   20  Female"))

此外,假设您想编制汇总表,打印出饮用葡萄酒、啤酒和水的频率。

我就是这样解决的。

con<-apply(df[,c(2:4)], 2, table)
con_P<-prop.table(con,2)

这使我能够以我想要的方式完成编译条形图的最终目标:

barplot(con_P)

效果很好。没问题。现在,让我们按如下方式调整数据集:我们将水的所有条目设置为 1。

df<-data.frame(read.table(header = TRUE, text = "
ID  Wine    Beer    Water   Age Gender
1   0   1   1   20  Male
2   1   0   1   38  Female
3   0   0   1   32  Female
4   1   0   1   30  Male
5   1   1   1   30  Male
6   1   1   1   26  Female
7   0   1   1   36  Female
8   0   1   1   29  Male
9   0   1   1   33  Female
10  0   1   1   20  Female"))

如果我现在运行以下命令:

con<-apply(df[,c(2:4)], 2, table)
con_P<-prop.table(con,2)

它在第二行之后给我以下错误消息:Error in margin.table(x, margin) : 'x' is not an array!

通过本论坛的另一个问题,我了解到以下内容可以帮助我解决这个问题:

con_P <- lapply(con, function(x) x/sum(x))

但是,如果我现在 运行

barplot(con_P)

R 不创建条形图:Error in -0.01 * height : non-numeric argument to binary operator。我猜是因为它不是数组!

我的问题是现在该怎么办(我如何将第二个示例中的 con_P 转换为数组?)。其次,如何使创建 prop.tables 和条形图的整个步骤更有效率?非常感谢任何帮助。

我们可以通过将列转换为 factor 并指定 levels。在第二个示例中,由于列在第二个和第三个中具有 0 和 1 值,我们将 levels 用作 0:1,然后获取 table 并转换为 [=16] 的比例=].并执行 barplot

 barplot(prop.table(sapply(df[2:4], 
         function(x) table(factor(x, levels=0:1))),2))

正在重现您的数据:

df<-data.frame(read.table(header = TRUE, text = "
ID  Wine    Beer    Water   Age Gender
1   0   1   1   20  Male
2   1   0   1   38  Female
3   0   0   1   32  Female
4   1   0   1   30  Male
5   1   1   1   30  Male
6   1   1   1   26  Female
7   0   1   1   36  Female
8   0   1   1   29  Male
9   0   1   1   33  Female
10  0   1   1   20  Female"))

con <-lapply(df[,c(2:4)], table)
con_P <- lapply(con, function(x) x/sum(x))

可以使用reshape2来融化数据:

library(reshape2)
df <- melt(con_P)

现在,如果您想使用 gpplot2,您可以使用 df 绘制条形图:

ggplot(df, aes(x = L1, y = value, fill = factor(Var1) )) + 
  geom_bar(stat= "identity") +
  theme_bw()

如果您想使用 barplot,您可以将 data.frame 重塑为 array:

array <- acast( df, Var1~L1)
array[is.na(array)] <- 0
barplot(array)