根据 dplyr 中另一个变量的子集更改值

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

我有一个数据集,其中包含来自一组进行过 ACL 重建的运动员的肌肉 activity 数据。我想重新分配肢体侧以指示 ACLR 肢体和未受伤的肢体。查看下面名为 EMG 的数据集,假设 John 有左 ACLR,Bob 有右 ACLR。

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

我希望数据集看起来像这样:

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

我原来的计划是按运动员对数据进行子集化,更改肢体值,然后将数据绑定回原始数据集中。

过程摘录如下:

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)

我确信有一种方法可以使用 dplyr 中的数据管道更快地完成此操作。我确信有一种方法可以根据指定条件替换变量的值。

逻辑是:如果 athlete==Bob 则将 Left 替换为 ACLR,将 Right 替换为 Uninjured。

感谢您提供的任何帮助。

马特

顺便说一句:您的逻辑和示例自相矛盾:您说 "Bob" 和 "Left" 表示 "ACLR" 但您的示例数据不同意。尽管如此:

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

(注意 xor 的使用 ... ifelse 中的检查基本上表示 "if in leftAthletes and right limb, or not in leftAthletes and left limb, then uninjured else ACLR"。)