1

Say I want to mutate a column ev1 for stim1 by finding the corresponding number in the Stimuli dataframe and finding its reward. For example

stim1 in data looks like this

  stim1
1     2
2     1
3     3
4     2
5     1

Stimuli looks like this

    number    reward
1        0 0.0000000
2        1 0.3333333
3        2 0.6666667
4        3 1.0000000...

Desired outcome

  stim1   ev1
1     2    0.6666667
2     1    0.3333333
3     3    1.0000000
4     2    0.6666667
5     1    0.3333333

My attempt of

data %>%  
  mutate(ev1=Stimuli$reward[which(Reward$number==stim1)]) -> data_modified

yields an error. Any help would be greatly appreciated!

user15791858
  • 175
  • 5

1 Answers1

1

We could do a left_join:

left_join() returns all rows from x, and all columns from x and y. Rows in x with no match in y will have NA values in the new columns. If there are multiple matches between x and y, all combinations of the matches are returned.

library(dplyr)
left_join(stim1, Stimuli, by=c("stim1"="number"))

Output:

stim1    reward
1     2 0.6666667
2     1 0.3333333
3     3 1.0000000
4     2 0.6666667
5     1 0.3333333
TarJae
  • 72,363
  • 6
  • 19
  • 66