简体   繁体   中英

how to not use if else to assign value to vectors iterately in R

Say I have a vector defined a= rep(NA, 10); I want to give its ith element a value for each iteration.

for(i in 1:10){
indexUsed[i] = largestGradient(X, y, indexUsed[is.na(indexUsed)], score)
}

as you see, I want use index[1:(i-1)] to calculate ith element, but for the first element, I want a NULL or whatever, special value there to let my function knows that it is empty (then it will handles this in the case for assigning value to the first element which is different from the next steps).

I do not know my writing is a good way to do that, usually how you do?

I don't have a better way of doing this than with a for loop, but would love to see other people's responses. However, it does seem to me that your code should read

  indexUsed[i] <- largestGradient(X, y, indexUsed[!is.na(indexUsed)], score)

For i=1 , your indexUsed[!is.na(indexUsed)] will be empty, and should be your based case in your function. For every other iteration, it will retrieve elements 1 through i-1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM