2017-03-16 35 views
0

下面是我的数据帧:使用tidyr/dplyr功能的汇总数据

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))) 
+0

'df%>%group_by(Species,Type [1])%>%summarize(m1 = mean(Contents),var1 = var(Contents))' – timfaber

+1

您应该花时间阅读'dplyr'教程,因为这段代码似乎有点偏离。应该是更类似于'Item%>%group_by(Type,Species)%>%summarize(mean = mean(Contents))'YOu不应该在基本dplyr语句中使用'$',我不确定你的意图是与'[2]'有关,但是这似乎也有点不合适。 – MrFlick

回答

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

+0

有没有办法让这个更具体,隔离只是类型f项目? –

+0

是这样的,你的意思是:'df%>%filter(Type ==“f”)%>%group_by(Species)%> mutate(meanByTypeandSpecies = mean(Contents.kg。))' –

0

请尽量使用管道工具及归纳组,让您的汇总统计:

Item %>% 
    group_by(Species, Type) %>% 
    summarise(
       mean = mean(Contents.kg.), 
       variance = var(Contents.kg.) 
    ) 
+0

这提供了相同的意味着每种物种和种类的组合。 –