为何R代码中列表s和d仅保留单个值?求调试建议
R编程问题排查与修正
任务要求
Use sample() to randomly select m integers from a vector y.
If input values are less than or equal to 100 & divisible by 3, then assign these values into a vector s.
If input values are greater than 100 & divisible by 4, then assign these values into a vector d.
Return a list l which contains the selected m integers, s & d.
Do not use the function which()
Apply the function to a sample which contains 20 randomly selected integers from vec = c(1:200). Show the output.
用户编写的代码
a <- c(99, 33, 104, 98, 108, 105) myfun <- function(y){ x <- sample(y) s <- NULL d <- NULL for(i in x){ if (i<=100 && i%%3==0) s <- print(i) if (i>100 && i%%4==0) d <- print(i) } s <- sapply(s, list) d <- sapply(d, list) l <- list(s,d) l[["d"]] <- d # trying to label values in vector d l[["s"]] <- s # trying to label values in vector s return(l) } myfun(a)
问题原因
- 赋值逻辑错误:循环中使用
s <- print(i)和d <- print(i)的方式,每次满足条件时都会直接覆盖s或d的现有值,而非追加新元素。比如第一个符合s条件的元素是99,s会被设为99;后续遇到33时,s又会被替换成33,最终仅保留最后一个符合条件的元素。 - 冗余的
sapply操作:用sapply(s, list)会把单个值转成嵌套列表,破坏了原本的向量结构,完全没有必要。 - 列表构建逻辑混乱:先创建无名列表
l <- list(s,d),之后又重新赋值l[["d"]]和l[["s"]],导致列表中出现重复键值,且初始的无名元素仍会保留。
解决建议
修正后的代码
# 生成任务要求的20个随机样本 vec <- 1:200 sample_y <- sample(vec, 20) myfun <- function(y, m = length(y)){ # 随机选择m个整数 x <- sample(y, size = m) s <- c() d <- c() for(i in x){ if (i <= 100 && i %% 3 == 0){ s <- c(s, i) # 追加元素到向量s中 } else if (i > 100 && i %% 4 == 0){ d <- c(d, i) # 追加元素到向量d中 } } # 构建清晰的命名结果列表 result_list <- list(selected_integers = x, s = s, d = d) return(result_list) } # 调用函数并输出结果 myfun(sample_y)
关键修正点
- 向量元素追加:用
s <- c(s, i)替代直接赋值,确保符合条件的元素会被追加到向量末尾,而非覆盖原有值。 - 规范列表构建:直接创建包含
selected_integers(选中的整数)、s、d的命名列表,避免结构混乱。 - 完善函数参数:新增
m参数(默认值为输入向量长度),更贴合任务中“随机选择m个整数”的要求。 - 移除冗余操作:删除无意义的
sapply调用,保留s和d的向量格式。
内容的提问来源于stack exchange,提问作者LeAnn Hall
相关产品推荐
相关产品推荐

