R 添加一列,其中包含具有最大频率的对象的值
我有一个矩阵:R 添加一列,其中包含具有最大频率的对象的值,r,matrix,max,subset,frequency,R,Matrix,Max,Subset,Frequency,我有一个矩阵: mat=matrix(c(1,1,1,2,2,2,3,4, 4,4,4,4,4,3,5,6, 3,3,5,5,6,8,0,9, 1,1,1,1,1,4,5,6),nrow=4,byrow=TRUE) print(mat) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [1,] 1 1 1 2 2 2 3 4 [2
mat=matrix(c(1,1,1,2,2,2,3,4,
4,4,4,4,4,3,5,6,
3,3,5,5,6,8,0,9,
1,1,1,1,1,4,5,6),nrow=4,byrow=TRUE)
print(mat)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1 1 1 2 2 2 3 4
[2,] 4 4 4 4 4 3 5 6
[3,] 3 3 5 5 6 8 0 9
[4,] 1 1 1 1 1 4 5 6
以及一个子集,其中包含我要应用函数的行的索引:
subset=c(2,4)
我想在矩阵“mat”中添加一个新列,该列仅包含我指定的子集,行中具有最大频率的对象的值
在这种情况下:
- 对于第1行,我希望在新列中有一个空单元格
- 对于第2行,我希望在新列中有值“4”
- 对于第3行,我希望在新列中有一个空单元格
- 对于第4行,我希望在新列中有值“1”
mat2=矩阵(c(24,1,3,2,4,4,4,4,4,3,2,5,1,3,5,1),nrow=4,byrow=TRUE)
以及子集:
subset=c(1,3)
我想用具有最大值的行的值的colname来替换矩阵的NA
(第一个子集合中的其余行)
在本例中,第一行为“1”,第三行为“4”。您正在寻找模式。不幸的是,R不提供内置模式函数。但写一本自己的并不难:
## create mode function
modeValue <- function(x) {
ux <- unique(x)
ux[which.max(tabulate(match(x, ux)))]
}
## add new column with NA
smat <- cbind(mat, NA)
## calculate mode for subset
smat[subset, ncol(smat)] <- apply(smat[subset, , drop=FALSE], 1, modeValue)
smat
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
# [1,] 1 1 1 2 2 2 3 4 NA
# [2,] 4 4 4 4 4 3 5 6 4
# [3,] 3 3 5 5 6 8 0 9 NA
# [4,] 1 1 1 1 1 4 5 6 1
##创建模式功能
modeValue这里有一个可以工作的函数。它为所有行计算此类值(模式),然后在需要时替换缺失:
myFunc <- function(x, myRows) {
myModes <- apply(mat, 1, FUN=function(i) {
temp<- table(i)
as.numeric(names(temp)[which.max(temp)])
})
myModes[setdiff(seq.int(nrow(x)), myRows)] <- NA
myModes
}
要将其添加到矩阵中,只需使用cbind
:
cbind(mat, myFunc(mat, c(2,4)))
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,] 1 1 1 2 2 2 3 4 NA
[2,] 4 4 4 4 4 3 5 6 4
[3,] 3 3 5 5 6 8 0 9 NA
[4,] 1 1 1 1 1 4 5 6 1
myFunc(mat, c(2,4))
[1] NA 4 NA 1
cbind(mat, myFunc(mat, c(2,4)))
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,] 1 1 1 2 2 2 3 4 NA
[2,] 4 4 4 4 4 3 5 6 4
[3,] 3 3 5 5 6 8 0 9 NA
[4,] 1 1 1 1 1 4 5 6 1