【问题标题】:Use qualitative data to draw barplots使用定性数据绘制条形图
【发布时间】:2016-01-20 17:47:55
【问题描述】:

我正在寻找一种解决方案来使用这种类型的数据集,该数据集显示在 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)的百分比。 目的是能够生成这种类型的图表:

有人对数据转换和条形图有任何想法吗?

【问题讨论】:

  • 你到底是如何从 dat 获得 dat2 的?
  • Sp 无关紧要吗?我没有看到它是如何使用的。
  • @rawr,经过一番思考,我想通了。他正在计算该列的ys 的数量,然后除以ys 的每个ForTyp 值的总数。所以对于ForTyp = 1,总共有7个yToxitolNitrotol各有3个,Poustol各有1个。所以 3/7、3/7、1/7。

标签: r dataframe bar-chart transformation


【解决方案1】:

这是使用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]))

【讨论】:

  • 獾,非常感谢,您的解决方案完美地完成了这项工作!干杯!
  • 作为替代方案,您可以在 t(prop.table(rowsum((dat[3:5] == "y") + 0, dat[[2]]), margin = 1) * 100) 上使用 barplot
猜你喜欢
  • 2017-09-27
  • 2021-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-18
  • 1970-01-01
  • 2023-03-30
  • 2020-06-23
相关资源
最近更新 更多