Jasperovic
Jasperovic

Reputation: 107

R sample row from matrix and set numeric values to 0

I want to sample a row from a matrix and then set all numeric values in that sampled row to 0.

Data

matrix = structure(c('Sp1', 'Sp2', 'Sp3', 'Sp4', 1, 1, 1, 0, 0, 0, 1, 1, 0, 
0, 0, 1), .Dim = c(4L, 4L), .Dimnames = list(NULL, c("", "col1", "col2", "col3")))

Calc sums

matrix = `colnames<-`(cbind(matrix, rowSums(`class<-`(matrix[,-1], 'numeric'))),c(colnames(matrix), 'Sums'))

Output

           col1 col2 col3 Sums
[1,] "Sp1" "1"  "0"  "0"  "1" 
[2,] "Sp2" "1"  "0"  "0"  "1" 
[3,] "Sp3" "1"  "1"  "0"  "2" 
[4,] "Sp4" "0"  "1"  "1"  "2" 

So it creates a matrix then calculates the Sums. Now I want it to sample a random row, set all values in numeric part to 0 and recalculate the Sums.

So far I got this:

sample <- matrix[sample(nrow(matrix),size=1,replace=FALSE),]

Upvotes: 3

Views: 104

Answers (1)

akrun
akrun

Reputation: 887138

I would have done this by either converting to 'data.frame' or using the first column as rownames to keep the matrix as numeric. If you have multiple class in the dataset, it would be better to have 'data.frame' because 'matrix' can have only a single class. Even if there is a single element that is character, the whole matrix will be converted to 'character' class. In the below example, a matrix is created with 'sps' as the row names. By doing this, we can make the code simple instead of converting back to 'numeric'.

m1 <- matrix(c(1,1,1,0, 0, 0, 1, 1, 0, 0,0, 1), nrow=4, ncol=3, 
         dimnames=list(paste0('sp', 1:4), paste0('col', 1:3)))
m2 <- cbind(m1, Sums=rowSums(m1))

m1[sample(nrow(m1), 1, replace=FALSE),] <- 0
cbind(m1, Sums=rowSums(m1))

Or an elegant option suggested by @nicola

m2*sample(c(rep(1,nrow(m2)-1),0))

About naming the object as 'matrix',

library(fortunes)
fortune('dog')

Firstly, don't call your matrix 'matrix'. Would you call your dog 'dog'? Anyway, it might clash with the function 'matrix'. -- Barry Rowlingson R-help (October 2004)

Upvotes: 2

Related Questions