R:apply/Lappy:如果列中的所有条目都是1',如何创建条形图;s
想象一下,您拥有以下数据集:R:apply/Lappy:如果列中的所有条目都是1',如何创建条形图;s,r,bar-chart,apply,lapply,R,Bar Chart,Apply,Lapply,想象一下,您拥有以下数据集: 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
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"))
它工作得很好。没问题。现在,让我们对数据集进行如下调整:我们将水的所有条目设置为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"))
然而,如果我现在跑步
barplot(con_P)
R不创建条形图:在-0.01*高度中出错:二进制运算符的非数字参数
。我想这是因为它不是数组
我的问题是现在要做什么(第二个示例中我如何将
con_p
转换为数组?)。其次,如何使创建prop.tables和条形图的整个步骤更加高效?非常感谢您的帮助。我们可以通过将列转换为指定了级别的因子。在第二个示例中,由于列在第2和第3列中有0和1值,我们使用级别作为0:1
,然后获取表
,并使用属性表
转换成比例。然后进行条形图
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))
现在,如果要使用gpplot2
可以使用df
绘制条形图:
ggplot(df, aes(x = L1, y = value, fill = factor(Var1) )) +
geom_bar(stat= "identity") +
theme_bw()
如果要使用条形图
,可以将数据框
重新整形为数组
:
array <- acast( df, Var1~L1)
array[is.na(array)] <- 0
barplot(array)
数组!我仍然需要消化你提出的建议,但效果很好!我很好奇地问,他们没有引起这个问题的因素是什么。谢谢你的快速回复@DomB通过在指定了级别的情况下将转换为因子
,表
输出给出了第4列中缺失值0的0
频率,并且当列表
的长度相同时,sapply
输出将转换为矩阵
。否则,它仍然是一个列表
。!谢谢你。我仍然不能完全确定发生了什么。但现在要由我来决定了!!谢谢你!更多的东西要消化!
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))
library(reshape2)
df <- melt(con_P)
ggplot(df, aes(x = L1, y = value, fill = factor(Var1) )) +
geom_bar(stat= "identity") +
theme_bw()
array <- acast( df, Var1~L1)
array[is.na(array)] <- 0
barplot(array)