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 me 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 &d ?任何建议吗?

在你的代码中sd不是列表,在for循环中它们被替换为每个i

this will work

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 <- append(s, print(i))
if (i>100 && i%%4==0)
d <- append(d, print(i))
}
l <- list(s= s,d= d)
return(l)
}
myfun(a)

最新更新