1

Currently I have data in this "wide" format:

|Participant|Banana|Apple|Orange|
|-|-|-|-|
|P1|0|0|0|
|P2|1|1|1|
|P3|0|0|0|

Ideally, I want to convert these data to long format for mixed models, i.e.,

|Participant|Item|Accuracy|
|-|-|-|
|P1|Banana|0|
|P1|Apple|0|
|P1|Orange|0|
|P2|Banana|1|
|P2|Apple|1|
|P2|Orange|1|
|P3|Banana|0|
|P3|Apple|0|
|P3|Orange|0|

(for some reason my tables are breaking, sorry folks.)

Code to reproduce

dat <- data_frame(
  Participant = paste0("P", 1:3),
  Banana = sample(0:1, 3, TRUE),
  Apple = sample(0:1, 3, TRUE),
  Orange = sample(0:1, 3, TRUE),
)

Been combing through a few posts and there are bits and pieces of the answer around but I can't quite put it together re: extracting and splicing the participants and transposing their rows.

Thanks for any help.

vesalius
  • 27
  • 4

2 Answers2

4

dplyr

tidyr::pivot_longer(wide, -Participant, names_to = "Item", values_to = "Accuracy")
# # A tibble: 9 x 3
#   Participant Item   Accuracy
#   <chr>       <chr>     <int>
# 1 P1          Banana        0
# 2 P1          Apple         0
# 3 P1          Orange        0
# 4 P2          Banana        1
# 5 P2          Apple         1
# 6 P2          Orange        1
# 7 P3          Banana        0
# 8 P3          Apple         0
# 9 P3          Orange        0
r2evans
  • 141,215
  • 6
  • 77
  • 149
1

You may try

library(dplyr)
library(reshape2)

dat %>%
  melt %>%
  rename(., Accuracy = value, Item = variable) %>%
  arrange(Participant)


  Participant   Item Accuracy
1          P1 Banana        0
2          P1  Apple        1
3          P1 Orange        0
4          P2 Banana        1
5          P2  Apple        0
6          P2 Orange        1
7          P3 Banana        1
8          P3  Apple        1
9          P3 Orange        1

Thanks to @r2evans

melt(dat, variable.name = "Accuracy", value.name = "Item")

  Participant Accuracy Item
1          P1   Banana    0
2          P2   Banana    1
3          P3   Banana    1
4          P1    Apple    1
5          P2    Apple    0
6          P3    Apple    1
7          P1   Orange    0
8          P2   Orange    1
9          P3   Orange    1
Park
  • 14,771
  • 6
  • 10
  • 29
  • 3
    Or just `melt(dat, variable.name = "Accuracy", measure.name = "Item")` without the need for pipes or renaming. – r2evans Dec 03 '21 at 01:40
  • 2
    @r2evans Wow. I didn't notice that. By the way, it seems that `value.name` works. Thanks a lot! – Park Dec 03 '21 at 01:45
  • 2
    I did mean `value.name=`, thanks for catching that typo ... I was playing with other reshaping and didn't QA/check what I typed, sorry about that. – r2evans Dec 03 '21 at 01:58
  • 2
    @r2evans Not a problem! I'm so grateful to remind `melt` function have those arguments. I usually tends to let them `variable` and `value`. Thanks again reminding me :D – Park Dec 03 '21 at 02:02