【发布时间】:2015-05-18 11:12:52
【问题描述】:
我想从矩阵中采样一行,然后将该采样行中的所有 numeric 值设置为 0。
数据
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")))
计算总和
matrix = `colnames<-`(cbind(matrix, rowSums(`class<-`(matrix[,-1], 'numeric'))),c(colnames(matrix), 'Sums'))
输出
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"
所以它创建一个矩阵然后计算总和。现在我希望它对随机行进行采样,将 数字部分 中的所有值设置为 0 并重新计算总和。
到目前为止,我得到了这个:
sample <- matrix[sample(nrow(matrix),size=1,replace=FALSE),]
【问题讨论】: