r - 在某些条件下转换向量中的矩阵值
问题描述
我想在某些条件下转换向量中的矩阵值。在我的例子中:
# 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"
请问,有什么想法吗?
解决方案
这是一个矢量化选项 -
#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"
推荐阅读
- return-value - 作为消息发送/接收值或从文件中写入/读取值
- r - 使用具有cooks.distance函数的influence.lme(汽车包)以及来自R中nlme的lme模型
- c - 将指针传递给 C 中的函数
- python - 深入 MQTT 的话题
- python - 使 numpy.random 生成的数字在不同函数之间保持一致
- java - 为什么这会一直输出 null 并且无法正常工作?
- c++ - 从字符串 C++ 中提取某些整数
- javascript - Chrome keydown 事件的 keyCode 错误
- javascript - 如果模型被覆盖,Vue.js 指令 v-html 不会更新
- reactjs - React 中的嵌套子组件 + 渲染新数据