2014-10-30 67 views
4

我試圖用dplyr做到以下幾點:使用dplyr的GROUP_BY進行拆分申請,結合

tapply(iris$Petal.Length, iris$Species, shapiro.test) 

我想通過拆分的Speicies Petal.Lengths,並應用功能,在這種情況下, shapiro.test.我讀了這個SO question和相當數量的其他網頁。我是那種能夠將變量分成不同的小組,利用do

iris %>% 
    group_by(Species) %>% 
    select(Petal.Length) %>% 
    do(print(.$Petal.Length)) 

[1] 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 1.5 1.6 1.4 1.1 1.2 
[16] 1.5 1.3 1.4 1.7 1.5 1.7 1.5 1.0 1.7 1.9 1.6 1.6 1.5 1.4 1.6 
[31] 1.6 1.5 1.5 1.4 1.5 1.2 1.3 1.4 1.3 1.5 1.3 1.3 1.3 1.6 1.9 
[46] 1.4 1.6 1.4 1.5 1.4 
[1] 4.7 4.5 4.9 4.0 4.6 4.5 4.7 3.3 4.6 3.9 3.5 4.2 4.0 4.7 3.6 
[16] 4.4 4.5 4.1 4.5 3.9 4.8 4.0 4.9 4.7 4.3 4.4 4.8 5.0 4.5 3.5 
[31] 3.8 3.7 3.9 5.1 4.5 4.5 4.7 4.4 4.1 4.0 4.4 4.6 4.0 3.3 4.2 
[46] 4.2 4.2 4.3 3.0 4.1 

列的「分裂」成組似乎是工作。但是,將這些作品傳遞給shapiro.test的方式仍然讓我難以置信。我看到group_by不同於分成

我試過很多的變化,其中包括:

iris %>% 
    group_by(Species) %>% 
    select(Petal.Length) %>% 
    summarise(shapiro.test) 

iris %>% 
    group_by(Species) %>% 
    select(Petal.Length) %>% 
    summarise_each(funs(shapiro.test)) 

# Error: expecting a single value 

我怎樣才能讓dplyr運行shapiro.test()三次,每次一個物種Petal.Lengths?

回答

6

我可以看到兩種方法來完成它,具體取決於您希望如何使用輸出。你可以從shapiro.test中取出summarise中的p值。或者,您可以使用do並將每個測試的結果保存在列表中。

library(dplyr) 

隨着summarise,拉出只是p值:

iris %>% 
    group_by(Species) %>% 
    summarise(stest = shapiro.test(Petal.Length)$p.value) 

    Species  stest 
1  setosa 0.05481147 
2 versicolor 0.15847784 
3 virginica 0.10977537 

使用do

tests = iris %>% 
    group_by(Species) %>% 
    do(test = shapiro.test(.$Petal.Length)) 

# Resulting list 
tests$test 

[[1]] 

    Shapiro-Wilk normality test 

data: .$Petal.Length 
W = 0.955, p-value = 0.05481 


[[2]] 

    Shapiro-Wilk normality test 

data: .$Petal.Length 
W = 0.966, p-value = 0.1585 


[[3]] 

    Shapiro-Wilk normality test 

data: .$Petal.Length 
W = 0.9622, p-value = 0.1098 
+0

謝謝@aosmith。將總結的結果存儲到列表中是一個巧妙的技巧。 – 2014-10-31 21:35:03

+1

真棒,當我能夠實現這一點時,我大聲高喊,稍微調整以從t.test中提取多個統計信息:'dfz%>%group_by(tooth,position)%>%summarize(tt.est = t.test(diff)$ estimate,tt.pv = t.test(diff)$ p.value)' – Paul 2015-04-26 05:10:31

+0

如果'iris'確實是一個MySQL表?我不斷收到'Stopifnot(is.numeric(x)):object'{column_name}'找不到'錯誤。 – adib 2015-05-24 08:00:14

1

如果使用tidy()功能從broom package,轉的shapiro.test()輸出進入data.frame然後你可以使用do()

iris %>% 
    group_by(Species) %>% 
    do(tidy(shapiro.test(.$Petal.Length))) 

這給了你:

Source: local data frame [3 x 4] 
Groups: Species [3] 

Species statistic p.value      method 
     <fctr>  <dbl>  <dbl>      <fctr> 
1  setosa 0.9549768 0.05481147 Shapiro-Wilk normality test 
2 versicolor 0.9660044 0.15847784 Shapiro-Wilk normality test 
3 virginica 0.9621864 0.10977537 Shapiro-Wilk normality test 

這是從我的answere here調整。