R语言函数内向量元素移除失效问题求助
问题分析与解决方案
核心问题
ele_remover函数当前是通过索引位置移除元素(original[-remove]),但你调用时传入的remove.crop.combo = c(12,13)是要移除的元素值,两者逻辑完全不匹配。new.combination是字符类型向量(比如"12"、"13"),但传入的remove.crop.combo是数值类型,类型不匹配导致无法定位到目标元素。
修正方案
推荐方案:修改ele_remover为按值移除
调整函数逻辑,让它根据元素值过滤,同时统一类型避免匹配失败:
ele_remover <- function(original, remove){ # 统一转为字符类型,解决数值/字符不匹配问题 remove <- as.character(remove) # 保留不在移除列表中的元素 output <- original[!original %in% remove] output }
备选方案:按索引移除(需先转换索引)
如果要保留按索引移除的逻辑,需要先找到目标元素对应的索引位置,再传入ele_remover:
ICD4 <- function(num.plots = 240, num.crops = 6, remove.crop.combo){ combination.a <- apply(combn(1:num.crops,2),2,paste0,collapse="") combination.b <- apply(combn(num.crops:1,2),2,paste0,collapse="") new.combination <- c(combination.a,combination.b) # 先找到要移除元素的索引位置 remove_indices <- which(new.combination %in% as.character(remove.crop.combo)) combination <- ele_remover(new.combination, remove_indices) comb.x <- sort(as.numeric(combination)) comb.each <- ceiling(num.plots/length(comb.x)) crop.combinations <- rep(comb.x, each=comb.each) output <- comb.x }
验证
运行修改后的ICD4(240, 6, c(12,13)),输出结果中会正确移除12和13这两个元素。
内容的提问来源于stack exchange,提问作者Aoxiang Xin
相关产品推荐
相关产品推荐

