gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:37:26 25 4
gpt4 key购买 nike

我有一个数据集,其中包含一组接受过 ACL 重建的运动员的肌肉事件数据。我想重新分配肢体侧以指示 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

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

过程摘录如下:

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肢体,然后未受伤,否则 ACLR"。)

关于r - 根据 dplyr 中另一个变量的子集更改值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30447396/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com