我希望我能从你的大脑中挑选出如何将我的数据转换成R中的长格式。
我想将条件、发色团和源检测器从数据中的变量名称中分离出来。下面我粘贴了一些示例(但是数据框架中还有更多的变量)。因此,我需要选择“愤怒”和“快乐”,并将它们放在一个可变的“状态”中,然后是发色团Hbo、HbR和Hbt,最后是源探测器对"1,1“和"1,2”(可能是在逗号前后搜索和拖动文本,因为我有49个这样的组合)。
示例变量名:
AngryHRFHbO,1,1 AngryHRFHbR,1,1 AngryHRFHbT,1,1 AngryHRFHbO,2,1 AngryHRFHbT,2,1 AngryHRFHbT,2,1幸福HRFHbR,4,1幸福HRFHbR,4,1幸福HRFHbR,2,2 2,2,2,2幸福HRFHbR,2,2幸福
谢谢你的帮助!
一切顺利,卡罗琳
发布于 2020-09-02 20:36:59
谢谢你的帮助!我能够用这个来得出我需要的结论。见下文:
df2 <- full_data %>%
pivot_longer(-c("ID", "time"), names_to = "Name", values_to = "Value") %>%
mutate(Name = str_replace_all(Name, regex("\\."), "_")) %>% #you can ignore this line
if the variables have the comma
mutate(Condition = str_extract(Name, regex("Angry|Happy|Fearful")),
Chromophore = str_extract(Name, regex("HbO|HbR|HbT", ignore_case = TRUE)),
Channel = str_extract_all(Name, regex("\\d+[_]\\d+$"))) %>%
select(c("ID", "time", "Name", "Condition", "Chromophore", "Channel", "Value"))发布于 2020-08-13 14:39:51
我做了一个与上面描述的数据类似的数据
library(tidyverse)
library(stringr)
df <- data.frame(obs = 1, "AngryHRFHbO,1,1" = 1, "AngryHRFHbR,1,1" = 0, "AngryHRFHbT,1,1" = 3, "AngryHRFHbO,2,1" = 9, "AngryHRFHbR,2,1" = 0, "HappyHRFHbT,4,1" = 4)
# obs AngryHRFHbO.1.1 AngryHRFHbR.1.1 AngryHRFHbT.1.1 AngryHRFHbO.2.1 AngryHRFHbR.2.1 HappyHRFHbT.4.1
# 1 1 1 0 3 9 0 4这是一种解决问题的方法。
df2 <- df %>%
pivot_longer(-obs, names_to = "Name", values_to = "Value") %>%
mutate(Name = str_replace_all(Name, regex("\\."), ",")) %>% #you can ignore this line if the variables have the comma
mutate(Condition = str_extract(Name, regex("Angry|Happy")),
Chromophore = str_extract(Name, regex("Hbo|HbR|Hbt", ignore_case = TRUE)),
detector = str_extract(Name, regex("\\d[,]\\d$"))) %>%
select(-c(obs, Value))
# Name Condition Chromophore detector
# <chr> <chr> <chr> <chr>
# 1 AngryHRFHbO,1,1 Angry HbO 1,1
# 2 AngryHRFHbR,1,1 Angry HbR 1,1
# 3 AngryHRFHbT,1,1 Angry HbT 1,1
# 4 AngryHRFHbO,2,1 Angry HbO 2,1
# 5 AngryHRFHbR,2,1 Angry HbR 2,1
# 6 HappyHRFHbT,4,1 Happy HbT 4,1 https://stackoverflow.com/questions/63396650
复制相似问题