简体   繁体   中英

How can I replicate this loop with apply in R?

I have been learning how to code in R recently, so I'm not familiarized with apply at all. As far as I know loops are not so efficient in R, so I'm trying to use apply function but I'm not getting any results.

This is my loop:

encoder_output <- function(sequence, vocabulary){
  auxlist <- list()
  for (i in sequence) {
    encoded <- to_categorical(i, num_classes=vocabulary)
    auxlist <- append(auxlist, encoded)
  }
  
  arrOutput <- array(unlist(auxlist),dim =c(nrow(sequence),ncol(sequence),vocabulary))
  
  return(arrOutput)  
}

And here is my apply:

encode_output <- function(sequence, vocabulary){
  auxlist <- list()
  apply(sequence, 1,function(x){
    encoded <- to_categorical(x, num_classes=vocabulary)
    auxlist <- append(auxlist, encoded)
  
  })

  array <- array(unlist(auxlist), dim= c(nrow(sequence),ncol(sequence),vocabulary) )
  return(array)  
}

But in my apply function, I'm getting an error in unlist, because it says that auxlist is empty. I don't know what I'm doing wrong. Btw, sequence is a 2D matrix. I believe that this code is enough to solve my question, but if necessary I will update it with more code. Thanks guys: PS. I'm using keras library to user to_categorical.

Ah. This is the classic coding environment issue. The return function will only give you a result within the code, but not show up in your environment. So try this:

assign(New_array_Name,array = df,.GlobalEnv)

Another way to do it is to have it as an output to assign it to another 'external' variable. In this case, remove return(arrOutput) , replace it with arrOutput. And, in the console or wherever you run your code, use the following line.

variable <- encoder_output(...)

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