這裏工作了這一點使用功能從dplyr和tidyr,特別是gather
和spread
的方式。
library(dplyr)
library(tidyr)
df1 <- tribble(
~respondent, ~Q1, ~Q2, ~Q3, ~Q4,
1, "A", "B", "A", "C",
2, "B", "B", "B", "C",
3, "A", "C", "B", "C",
4, "A", "B", "B", "A"
)
df2 <- tribble(
~question, ~correct,
"Q1", "A",
"Q2", "B",
"Q3", "B",
"Q4", "C"
)
df1 %>%
gather(question, answer, -respondent) %>%
left_join(df2) %>%
mutate(compare = ifelse(answer == correct, 1, 0)) %>%
select(-answer, -correct) %>%
spread(question, compare)
#> Joining, by = "question"
#> # A tibble: 4 × 5
#> respondent Q1 Q2 Q3 Q4
#> * <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 1 1 1 0 1
#> 2 2 0 1 1 1
#> 3 3 1 0 1 1
#> 4 4 1 1 1 0
請提供一個小例子數據幀(一個或多個)和期望的輸出。見http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – coffeinjunky