使用tidyr / dplyr函数汇总数据

时间:2017-03-16 15:38:29

标签: r

以下是我的数据框:

  Species   Type  Contents (kg)
1       T      f           0.0710000
2       T      f           0.1100000
3       W      f           0.0200000
4       W      f           0.0200000
5       S      f           0.2100000
6       S      f           0.2800000
7       T      w           1.1400000
8       T      w           0.6000000
9       W      w           0.5600000
10      W      w           0.5600000
11      S      w           1.9800000
12      S      w           3.1200000

使用dplyr函数我得到了type f的均值和方差,但我也希望将结果除以species,并且想知道如何使用tidyr /来做到这一点dplyr功能。

这是我用来查找上面type f的均值和方差。

summarise(group_by(Item,Type[2]),Mean = mean(Item$Contents (kg)),Variance = var(Item$Contents (kg)))

2 个答案:

答案 0 :(得分:0)

dplyr相对简单,只需致电mutate

df <- read.table(text =
               " Row   Species   Type  Contents(kg)
                  1       T      f           0.0710000
                  2       T      f           0.1100000
                  3       W      f           0.0200000
                  4       W      f           0.0200000
                  5       S      f           0.2100000
                  6       S      f           0.2800000
                  7       T      w           1.1400000
                  8       T      w           0.6000000
                  9       W      w           0.5600000
                  10      W      w           0.5600000
                  11      S      w           1.9800000
                  12      S      w           3.1200000",
             header = TRUE, stringsAsFactors = FALSE)


library(dplyr)


df %>%
  group_by(Type, Species) %>%
  mutate(meanByTypeandSpecies = mean(Contents.kg.))

结果:

enter image description here

答案 1 :(得分:0)

请尝试使用管道工具并汇总以按组获取摘要统计信息:

$(document).ready(function() {

  var tester = document.getElementById('tester');

  Plotly.plot(tester, [{
    x: [1, 2, 3, 4, 5],
    y: [1, 2, 4, 8, 16]
  }], {
    margin: {
      t: 0
    }
  });
  tester.on('plotly_hover', function(data) {
    console.log(data)
  });
});