2017-05-03 60 views
1

我有調查回覆的數據框。我試圖看看有多少問題連續以相同的方式回答。計算未更改值的數量

#Data 
s <- structure(list(Student_ID = c("1234", "1234", "1234", "1234", 
"1234", "1234", "1234", "1234", "1234", "1234", "1234", "1234", 
"1234", "1234", "1234", "1234", "1234", "1234", "1234", "1234", 
"1234", "5678", "5678", "5678", "5678", "5678", "5678", "5678", 
"5678", "5678", "5678", "5678", "5678", "5678", "5678", "5678", 
"5678", "5678", "5678", "5678", "5678", "5678"), key = c("Q1.1", 
"Q1.2", "Q1.3", "Q1.4", "Q1.5", "Q1.6", "Q1.7", "Q1.8", "Q1.9", 
"Q2.1", "Q2.2", "Q2.3", "Q2.4", "Q2.5", "Q2.6", "Q2.7", "Q2.8", 
"Q2.9", "Q2.10", "Q2.11", "Q2.12", "Q1.1", "Q1.2", "Q1.3", "Q1.4", 
"Q1.5", "Q1.6", "Q1.7", "Q1.8", "Q1.9", "Q2.1", "Q2.2", "Q2.3", 
"Q2.4", "Q2.5", "Q2.6", "Q2.7", "Q2.8", "Q2.9", "Q2.10", "Q2.11", 
"Q2.12"), value = c(4, 5, 6, 4, 5, 7, 8, 4, 8, 4, 5, 7, 5, 6, 
8, 4, 3, 5, 4, 4, 4, 2, 2, 1, 1, 0, 1, 2, 1, 2, 1, 1, 2, 2, 1, 
2, 2, 4, 3, 1, 2, 1)), row.names = c(NA, -42L), .Names = c("Student_ID", 
"key", "value"), class = c("tbl_df", "tbl", "data.frame")) 

我已經試過這樣:

s %>% group_by(Student_ID) %>% mutate(strip = ifelse(value != lag(value,1,default = -1),1,0)) %>% print(n = 100) 

其正確標識,我應該開始(用0)計數的地方。我試圖用這個:

s %>% group_by(Student_ID) %>% mutate(strip = ifelse(value != lag(value,1,default = -1),1,lag(strip)+1)) %>% print(n = 100) 

但收到一個錯誤,指出找不到對象'strip'。

這是我想看到的內容:

#Answer column 
s$answer <- c(rep(1,19),2,3,1,2,1,2,1,1,1,1,1,1,2,1,2,1,1,2,1,1,1,1,1) 
+0

這裏有'data.table'' setDT(s)[,answer:= seq_len(.N),。(cumsum(value!= shift(value,fill = -1)),Student_ID)] []' – akrun

回答

2

您可以通過使用cumsum其分組爲連續條紋做到這一點,然後用row_number()找到每個組內的索引:

s %>% 
    group_by(Student_ID) %>% 
    group_by(group = cumsum(value != lag(value, default = -1)), add = TRUE) %>% 
    mutate(answer = row_number()) %>% 
    ungroup()