Home > Blockchain >  Iterating Through Vectors in For Loops and Functions
Iterating Through Vectors in For Loops and Functions

Time:02-06

I'm a beginner in R and I'm trying to create a function that takes vectors as input and returns numbers greater than 10 using for loops. I don't know why my function won't iterate through the entire vector; it only returns a single number.

hi <- function(x) {
  for (i in x) {
    if (i<10) {
      next
    }
  }
  print(i)
}
  
testvec1 <- c(2, 7, 10, 26, 18, 32)
hi(testvec1)

if I ran the code above, it returns 32. I also tried specifying the position instead:


fxn <- function(x) {
  for (i in 1:length(x)) {
    if (x[i]<10) {
      next
    }
  }
  print(x[i])
}
  
fxn(testvec1)

it also only returns 32. The logic seems correct to me so I wonder if there's anything about the grammar that I did not grasp. Thank yall.

CodePudding user response:

this will print and store your output as a list which you can then unlist


hi <- function(x) {
  for (i in x) {
    if (i<10) {
      next
    }
    print(i)
    storeoutput[[k]] <<- i
    k = k 1
  }
}

k=1
storeoutput <- list()
testvec1 <- c(2, 7, 10, 26, 18, 32)
hi(testvec1)


unlist(storeoutput)

CodePudding user response:

i managed to have it return a vector by adding an empty vector before the for loop inside the function

  • Related