我正在寻找使用此类数据集的解决方案,该数据集显示在ForTyp(森林类型)中采样的Sp(物种)并且具有毒性(Toxitol,Nitrotol,Poustol):N / A表示数据集中没有信息(一个空白的地方):
dat<-read.table(text = "Sp ForTyp Toxitol Nitrotol Poustol
A 1 y y N/A
B 1 N/A y y
C 1 y y N/A
D 1 y N/A N/A
E 2 y N/A N/A
F 2 N/A N/A y
A 3 y y N/A
B 3 N/A y y
C 3 y y N/A",header=T)
我正在寻找一种解决方案来转换以前的数据帧:
dat2<-read.table(text = "ForTyp Toxitol Nitrotol Poustol
1 42,85 42,85 14,29
2 50 0 50
3 33,33 50 16,67", header=T)
此数据框显示不同ForTyp(森林类型)的每列(Toxitol,Nitrotol,Poustol)的百分比。 目的是能够生成这种类型的图表:
有人对数据转换和条形图有任何想法吗?
答案 0 :(得分:2)
这是使用plyr
包进行处理的方法。要使情节漂亮,需要做一些工作,但目标已经实现。
library(plyr)
dat[,3:5] <- ifelse(dat[,3:5] == "y",1,0)
dat2 <- ddply(.data = dat,.(ForTyp), .fun = function(x) {
Toxitol = sum(x$Toxitol)
Nitrotol = sum(x$Nitrotol)
Poustol = sum(x$Poustol)
props <- prop.table(c(Toxitol,Nitrotol,Poustol))
}
)
barplot(as.matrix( t( dat2[2:4] *100) ),names.arg = unique( dat[,2]),legend.text = colnames( dat[,3:5]))