如何在R中随机打乱物种列表时保留指定物种的位置不变
问题:保留指定物种位置的同时随机打乱其余物种
需求说明
给定物种名称列表,需保留指定物种的位置不变,随机打乱其余物种的位置:
- 完整物种列表:
names <- c("a","b","c","d","e","f","g")
- 需要保留位置的物种:
const_names <- c("b","c","e")
- 预期结果示例:
"g","b","c","f","e","d","a"
原代码问题分析
你写的i1 <- which(names != const_names)逻辑错误:const_names是向量,names != const_names会按元素循环比对(把names每个元素和const_names的元素依次匹配),而非判断names中的元素是否属于const_names,导致筛选出的位置完全错误,最终所有元素都被打乱。
正确解决方案
基础版本(不含NA)
先筛选出需要保留的位置,再对剩余位置的元素随机重排:
# 定义完整列表和需保留物种 names <- c("a","b","c","d","e","f","g") const_names <- c("b","c","e") # 获取需要保留的位置索引 keep_positions <- which(names %in% const_names) # 获取需要打乱的位置索引 shuffle_positions <- which(!names %in% const_names) # 对需打乱位置的元素随机抽样替换 names[shuffle_positions] <- sample(names[shuffle_positions]) # 查看结果 names
运行后b、c、e的位置保持不变,其余元素随机打乱,符合预期。
处理含NA的情况
如果列表包含NA,%in%会将NA视为匹配,需额外处理NA的位置,避免其被打乱:
names_with_na <- c("a","b",NA,"d","e","f","g") const_names <- c("b","c","e") # 同时保留指定物种和NA的位置 keep_positions <- which(names_with_na %in% const_names | is.na(names_with_na)) shuffle_positions <- which(!names_with_na %in% const_names & !is.na(names_with_na)) # 打乱剩余元素 names_with_na[shuffle_positions] <- sample(names_with_na[shuffle_positions]) names_with_na
内容的提问来源于stack exchange,提问作者Liam Lamberton
相关产品推荐
相关产品推荐

