2013-04-26 34 views
-1

假設我有以下類型的數據:Count函數

df <- data.frame(student = c("S1", "S2", "S3", "S4", "S5", "S2", "S6", "S1", "S7", "S8"), 
       factor = c("A", "A", "A", "A", "A", "B", "B", "C", "C", "D"), 
       year = c(1, 1, 1, 1, 1, 1, 1, 2, 2, 2), 
       count1 = c(0, 1, 0, 0, 0, 1, 0, 0, 0, 0), 
       count2 = c(1, 0, 0, 0, 0, 0, 0, 1, 0, 0)) 

我需要比典型的更有效的方式應用()函數來分析在給定年份裏,學生和班級的兩列。當學生在給定年份保持相同的因子水平時,函數返回零計數。當一個學生在某一年有多個因子水平時,每個學生的實例在單獨的因子水平上更新i + 1。

我想要一個單獨的計數/功能來分析數據集中的學生跨多年。例如,一個多年保持相同因子水平的學生的計數爲零。 如果在不同的年份發現學生具有不同的因子水平,則每個實例的計數會更新i + 1。

有超過10K的觀察,所以我在*申請的嘗試是非生產性的。也就是說,我已經能夠計算每個學生的唯一實例,但是隻有第一個唯一實例並不是所有學生的唯一實例(唯一ID)和因子。個人可以在幾年內或幾年內重複。

理想的輸出如下:

Student1,Factor.Count(在年),Factor.Count(間年)

+0

沒有樣本數據很難理解問題。請爲這裏的優秀人士添加可重複的樣本以幫助您。見http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – 2013-04-26 01:39:52

+0

編輯顯示代碼來模擬數據。 – 2013-04-26 01:48:29

+0

兩條評論。 1(稍微小一點):在'apply'變得太貴之前,10K的觀測值並不是你所需要的。 2(有些重大):它不完全清楚你想要什麼。更改您的示例數據,以便某些學生實際得到0分,併爲示例提供期望的結果。 – 2013-04-26 02:19:12

回答

0

這裏,讓你有一個命令鏈,採用因子相互作用,以找到在同一年一個學生的因素變化:

# Add up the occurrences of a student having multiple factors in the same year, 
# for each year 
in.each.year <- aggregate(factor~student:year, data=df, FUN=function(x) length(x)-1)[c(1,3)] 

# Total these up, for each student 
in.year <- aggregate(factor~student, data=in.each.year, FUN=sum) 

# The name was "factor". Set it to the desired name. 
names(in.year)[2] <- 'count1' 

# Find the occurrences of a student having multiple factors 
both <- aggregate(factor~student, data=df, FUN=function(x) length(x)-1) 
names(both)[2] <- 'both' 

# Combine with 'merge' 
m <- merge(in.year, both) 

# Subtract to find "count2" 
m$count2 <- m$both - m$count1 
m$both <- NULL 

m 
## student count1 count2 
## 1  S1  0  1 
## 2  S2  1  0 
## 3  S3  0  0 
## 4  S4  0  0 
## 5  S5  0  0 
## 6  S6  0  0 
## 7  S7  0  0 
## 8  S8  0  0 

這可以用自己的原始數據幀(合併不列count1count2):

merge(df, m) 
## student factor year count1 count2 
## 1  S1  A 1  0  1 
## 2  S1  C 2  0  1 
## 3  S2  A 1  1  0 
## 4  S2  B 1  1  0 
## 5  S3  A 1  0  0 
## 6  S4  A 1  0  0 
## 7  S5  A 1  0  0 
## 8  S6  B 1  0  0 
## 9  S7  C 2  0  0 
## 10  S8  D 2  0  0