在R中按subject组重新排序conditions因子的水平
按分组重新排序因子水平并排列数据框
原始数据
example <- data.frame( subject = c(rep(101,12), rep(102,12)), conditions = rep(c("selfimmneg", "selfimmneut", "selfrefneg", "socimmneg", "socimmneut", "socrefneg"), 4) ) example$conditions <- as.factor(example$conditions)
需求
按subject分组,将每个subject对应的conditions按指定顺序c("selfrefneg", "selfimmneg", "selfimmneut", "socrefneg", "socimmneg", "socimmneut")重新排列,最终得到每个subject下该顺序的因子重复2次的结果(如示例example_solution所示)。
解决方案
方法1:分组排序通用法(依赖dplyr)
适用于每个subject下各条件水平行数不固定的场景,通过分组排序实现:
library(dplyr) # 定义目标顺序 target_order <- c("selfrefneg", "selfimmneg", "selfimmneut", "socrefneg", "socimmneg", "socimmneut") example_sorted <- example %>% group_by(subject) %>% # 按目标因子顺序排列每组内的行 arrange(factor(conditions, levels = target_order), .by_group = TRUE) %>% ungroup() # 验证结果是否匹配示例 all.equal(example_sorted$conditions, example_solution$conditions)
方法2:直接构造结果(适配当前数据规则)
已知每个subject下每个条件水平恰好有2条记录时,可直接构造符合要求的列:
target_order <- c("selfrefneg", "selfimmneg", "selfimmneut", "socrefneg", "socimmneg", "socimmneut") # 构造对应顺序的conditions列 new_conditions <- rep(rep(target_order, each = 2), length(unique(example$subject))) example_sorted <- example %>% mutate(conditions = factor(new_conditions, levels = target_order)) %>% arrange(subject, conditions)
内容的提问来源于stack exchange,提问作者jo_
相关产品推荐
相关产品推荐

