首页 > 解决方案 > 在某些条件下转换向量中的矩阵值

问题描述

我想在某些条件下转换向量中的矩阵值。在我的例子中:

# Create my matrix
mymatrix <-matrix(
    
  # Create a numeric variable 
  abs(rnorm(300)),
    
  # No of rows
  nrow = 10,   
    
  # No of columns
  ncol = 3,         
    
  # By default matrices are in column-wise order
  # So this parameter decides how to arrange the matrix
  byrow = TRUE          
)
# Naming rows
rownames(mymatrix) = 1:10
   
# Naming columns
colnames(mymatrix ) = c("1", "2", "3")

mymatrix
#            1          2           3
#1  0.85882558 1.38755611 0.369197570
#2  1.58785948 1.13064411 1.542977629
#3  0.35293056 1.44036121 1.806414543
#4  0.02709663 1.25620400 0.794001157
#5  0.34426152 0.32365824 2.026024465
#6  0.03608507 1.12315562 1.072635275
#7  0.39055300 0.49463748 0.645037388
#8  0.33406392 0.63543332 0.005055208
#9  1.04796081 0.04062249 2.330948193
#10 0.42538451 0.24574490 0.268357588

我想myvector使用自定义规则将我的矩阵转换为向量():如果mymatrix[,1]是行中的最大值,mymatrix[,1]>=0.95然后向量结果是“1”,但如果mymatrix[,1]<0.95结果是“错误分类”,但mymatrix[,2]结果mymatrix[,3]是("2") 或 ("3") 是每行内的最大值。我想要的输出是:

myvector
#[1] "2" "1" "3" "2" "3" "2" "3" "2" "1" "misclassified"

请问,有什么想法吗?

标签: rmatrixvectordplyr

解决方案


这是一个矢量化选项 -

#Get the column number of max value in each row
res <- max.col(mymatrix)
#Get row number where column 1 is highest
inds <- which(res == 1)
#If those value is less than 0.95 make it 'misclassified'
res[inds][mymatrix[inds, 1] < 0.95] <- 'misclassified'
res

#[1] "2"        "1"             "3"             "2"             "3"            
#[6] "2"        "3"             "2"             "3"             "misclassified"

推荐阅读