2017-03-16 54 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

這提供了相同的意味着每種物種和種類的組合。 –