Here are some sample data. Each row is a different participant. Each participant completes five trials. In each trial, they pick one fruit from a set of 10 fruits (without replacement).
ID | trial_1 | trial_2 | trial_3 | trial_4 | trial_5 |
---|---|---|---|---|---|
01 | apple | orange | banana | peach | grapes |
02 | grapes | watermelon | mango | peach | apricot |
03 | pear | grapes | mango | orange | banana |
04 | watermelon | apple | peach | grapes | pear |
05 | banana | peach | apple | grapes | mango |
I want to create 10 new columns--one for each fruit--that has the trial number in it (or "NA" if no trial number):
ID | trial_1 | trial_2 | trial_3 | trial_4 | trial_5 | apple | apricot | banana | grapes | mango | orange | peach | pear | strawberries | watermelon |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
01 | apple | orange | banana | peach | grapes | 1 | NA | 3 | 5 | NA | 2 | 4 | NA | NA | NA |
02 | grapes | watermelon | mango | peach | apricot | NA | 5 | NA | 1 | 3 | NA | 4 | NA | NA | 2 |
03 | pear | grapes | mango | orange | banana | NA | NA | 5 | 2 | 3 | 4 | NA | 1 | NA | NA |
04 | watermelon | apple | peach | grapes | pear | 2 | NA | NA | 4 | NA | NA | 3 | 5 | NA | 1 |
05 | banana | peach | apple | grapes | mango | 3 | NA | 1 | 4 | 5 | NA | 2 | NA | NA | NA |
I could do that for each fruit column like this, but it seems very clunky:
mutate(apple = ifelse(trial_1 == "apple", 1,
ifelse(trial_2 == "apple", 2,
ifelse(trial_2 == "apple", 3,
ifelse(trial_2 == "apple", 4
ifelse(trial_2 == "apple", 5, "NA"))))))
I assume there is a much easier, neater solution to this, possibly using rowwise()
to match the fruit name and then just returning the last character (i.e., the number) of the column name. But I just can't work it out. Can you please help?