0

I have a data frame with the following column:

tibble [9,279 x 5] (S3: tbl_df/tbl/data.frame)
 $ id      : int [1:9279] 4119369 4119369 4119369 4119369 4119369 4119369 4119369 4119369 4119369 4119369 ...
 $ period  : int [1:9279] 1 2 3 4 5 1 2 3 4 5 ...
 $ trial   : num [1:9279] 1 1 1 1 1 2 2 2 2 2 ...
 $ decision: num [1:9279] 10 10 10 0 0 8 9 6 13 13 ...
 $ nature  : int [1:9279] 17 17 17 17 17 6 6 6 6 6 ...

so I want to use if else statement and for loop function to count the correct decision of each id in each trial. There are 5 periods in a trial and decision is between 1 and 20. The nature of each trial doesnt change. The decision rule is if decision of period 1 < nature, then decision should be between 10 and 20 for the rest of the trial. And if decision of period 1 > nature, then decision should be between 1 and 14 for the rest of the trial. My code at the moment is:

correct_override = function(period = 1:5, decision, nature){
  correct=0;
  if(decision[period==1]<=nature){
  for (p in period){
    d = decision[p]
    correct = correct + (d >= 10 & d <= 20) 
  }}else if (decision[period==1]>nature){
    for (p in period){
    d = decision[p]
    correct = correct + (d >= 1 & d <= 14)
  }
  } else{
    correct=0
  }
  return(correct)
  
} 

trial_dt = group_by(dt, id, trial) %>%
  summarise(correct_or =
              correct_override(
                period = period[period %in% 1:5],
                decision = decision[period %in% 1:5],
                nature = nature[period %in% 1:5]))

So as you can see, I created a function called correct_override but it doesnt do the work as I get a warming "the condition has length > 1 and only the first element will be used"

Ja Mah
  • 27
  • 4

0 Answers0