Change a value based on a subset of another variable in dplyr

I have a dataset containing muscle activity data from a group of athletes who have had ACL reconstruction. I want to remap the side of a limb to indicate an ACLR limb and an intact limb. Looking at the dataset called EMG below, suppose John had the left ACLR and Bob had the right ACLR.

athlete     limb     EMG_value
John        left         0.8
John        right        1.2
Bob         left         0.5
Bob         right        0.9

      

I would like the dataset to look like this:

athlete     limb       EMG_value
John        ACLR         0.8
John        uninjured    1.2
Bob         uninjured    0.5
Bob         ACLR         0.9

      

My original plan was to multiply the athlete's data, change the limb value, and then bind the data back to the original dataset.

An excerpt from the process looks like this:

John = subset(EMG, athlete=="John")

John$side<- as.character(John$side)

John$side[John$side=="Left"]="ACLR"
John$side[John$side=="Right"]="Uninjured"
John$side = as.factor(John$side)

Bob = subset(EMG, athlete=="Bob")

Bob$side<- as.character(Bob$side)

Bob$side[Bob$side=="Left"]="Uninjured"
Bob$side[Bob$side=="Right"]="ACLR"
Bob$side = as.factor(Bob$side)

EMG2 = rbind(Bob, John)

      

I am sure there is a way to make it faster using data in dplyr. I'm sure there is a way to replace the value of a variable based on a given condition.

The logic would be: if athlete == Bob replaces Left with ACLR and replaces Right with Ununjured.

Thanks for any help you can provide.

Matt

+3


source to share


1 answer


By the way: your logic and example contradict: you say "Bob" and "Left" means "ACLR", but your example data disagree. Nevertheless:

library(dplyr)
## generalizable so you can easily add other patients, etc
leftAthletes <- c('Bob')

mutate(acl, limb=ifelse(xor(athlete %in% leftAthletes, limb == 'left'),
                        'uninjured', 'ACLR'))
##   athlete      limb EMG_value
## 1    John uninjured       0.8
## 2    John      ACLR       1.2
## 3     Bob      ACLR       0.5
## 4     Bob uninjured       0.9

      



(Note the use xor

... the inside check ifelse

essentially says "if in left and right limbs or not in left and left limbs, then in an intact other ACLR.")

+2


source







All Articles