Reproducible example below. I have a simulation loop, within which I occasionally have rows I need to remove from a matrix. I have done this by entering an ‘NA’ value into the row I need to remove in a specific position, and then I have a line of code to remove any line with an NA. This has worked great so far. My issue is, I am now running simulations in a certain way that occasionally whittles my matrix down to a single row. Then this occurs, the matrix gets transformed into a ‘character’, and crashes the simulation.
Example:
mat<-matrix(1:10,5,2) #setting up a simplified example matrix
mat[3:5,1]<-NA #Giving 3 rows 'NA' values, for removal of these rows
mat<-mat[!is.na(mat[,1]),] #An example where my procedure works just fine
class(mat)
mat[2,1]<-NA #Setting 1 of the remaining 2 rows as NA
mat<-mat[!is.na(mat[,1]),] #Removing one of final two rows
class(mat) #No longer a matrix
Is there some way I can do this, where I don’t lose my formatting as a matrix at the end? I am assuming this issue is coming from my use of the “is.na” command, but I haven’t found a good way around using this.
To give a bit more insight into the issue, in case there is a MUCH better way to do this I am too naive to have found yet… In my real-life simulation, I have a column in the matrix that holds a ‘1’ when the individual in the given row is alive, and a ‘0’ when dead. When an individual (a single row) dies, (and the value goes from a ‘1’ to a ‘0’), I need to remove the row. The only way I knew how to do this was to change the ‘0’ to an ‘NA’ and then remove all rows with an NA. If there is a way to just remove the rows with a ‘0’ in a specific column that avoids this issue, that would be great!
By default, the
[function coerces the output into the lowest possible dimension. In your example, you have a two dimensional array (a matrix): when extracting a single row, it is coerced into a vector of characters.To avoid that, have a look at the
dropoption to the[function. You should be doing: