提取满足起止值条件的数值向量递减序列
提取满足条件的递减序列解决方案
需求说明
从数值向量中提取连续递减子序列,需满足:
- 序列首个值 >= 40
- 序列最后一个值 <= 20
示例数据
Mydata <- c(1, 5, 0, 10, 40, 30, 25, 20, 7, 34, 23, 55, 70, 42, 38, 22, 44, 33, 11, 17, 25)
R语言实现代码
# 定位所有符合条件的起始位置(值>=40) start_indices <- which(Mydata >= 40) # 初始化结果列表 result_list <- list() for (start in start_indices) { current_pos <- start current_seq <- Mydata[current_pos] # 向后遍历,收集连续递减的元素 while (current_pos < length(Mydata)) { next_val <- Mydata[current_pos + 1] if (next_val < current_seq[length(current_seq)]) { current_seq <- c(current_seq, next_val) current_pos <- current_pos + 1 } else { break } } # 检查序列末尾是否<=20,符合则加入结果 if (current_seq[length(current_seq)] <= 20) { result_list[[length(result_list) + 1]] <- current_seq } } # 输出最终结果 result_list
运行结果
执行代码后得到的结果列表包含两个子序列:
c(40, 30, 25, 20, 7)c(44, 33, 11)
内容的提问来源于stack exchange,提问作者Yang Yang
相关产品推荐
相关产品推荐

