Home > Software engineering >  Why does my code only print the last value in a list?
Why does my code only print the last value in a list?

Time:12-06

I am trying to solve this problem:

# 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)

Why do I only get one value in each part of the list, s & d? Any tips?

CodePudding user response:

in your code s and d are not lists, in the for loop they are replaced for each 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)
  • Related