给定以下测试矩阵:
testMatrix <- matrix( c(1,1,2,10,20,30,300,100,200,"A","B","C"), 3, 4)
colnames(testMatrix) <- c("GroupID", "ElementID", "Value", "Name")
在这里,我想找到每组的最大值,然后返回该列的名称。例如,我希望 1、A 和 2、C。如果与 max 有平局,那么第一场比赛就可以了。之后,我必须使用新列“GroupName”将其附加到矩阵
我怎样才能做到这一点?
我已经有了 Group, Max Value 组合:
groupMax <- aggregate (as.numeric(testMatrix[,3]), by=list( testMatrix[,1] ), max )
我用来向矩阵添加列的方式是这样的(假设已经有一个矩阵 groupNames 与 GroupID、名称组合):
testMatrix <- cbind ( testMatrix, groupNames[match( testMatrix[,1], groupNames[,1] ), 2] )