我有调查回复的数据框。我试图查看有多少问题以相同的方式连续回答。
#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)
但是会收到一个错误,即对象“剥离”&#39;无法找到。
以下是我希望看到的内容:
#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 :(得分: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()