2017-07-07 76 views
0

在Alan Agresti的線性和廣義線性模型的基礎中,作者指出二進制數據建模的分組和非分組數據存在差異。這種格式對於推斷無關緊要,但它對於合適的好處很重要。我很難在dplyr中以有效的方式從未分組的數據中獲取分組數據。dplyr中的分組數據

#ungrouped data 
x = c(rep(0,4),rep(1,4),rep(2,4)) 
y = c(c(1,0,0,0,1,1,0,0,1,1,1,1)) 
data = as_tibble(list(x=x,y=y)) 
> data 
# A tibble: 12 × 2 
     x  y 
    <dbl> <dbl> 
1  0  1 
2  0  0 
3  0  0 
4  0  0 
5  1  1 
6  1  1 
7  1  0 
8  1  0 
9  2  1 
10  2  1 
11  2  1 
12  2  1 

我們得到的分組數據的形式看起來應該像下面

x ntrials nsuccesses 
0  4   1 
1  4   2 
2  4   4 

我曾嘗試以下

data %>% 
group_by(x,y) %>% 
    tally() 
     x  y  n 
    <dbl> <dbl> <int> 
1  0  0  3 
2  0  1  1 
3  1  0  2 
4  1  1  2 
5  2  1  4 

的問題是,y被分成成功和失敗。

回答

1

您可以只用列X然後組總結基於y列

data %>% group_by(x) %>% summarise(ntrials = n(), nsuccesses = sum(y)) 
# the number of successes is the sum of y if y is binary 

# A tibble: 3 x 3 
#  x ntrials nsuccesses 
# <dbl> <int>  <dbl> 
#1  0  4   1 
#2  1  4   2 
#3  2  4   4 
+0

完美!謝謝! – Alex

+0

不客氣。祝你好運。 – Psidom