[英]Retrieving row and column names in R
因此,我有一個循環使用的矩陣TMatrix,我想將每個單元格的行和列名稱放入表中,該單元格包含的值不是有限的。 我嘗試執行以下操作,但行和列名稱一直不適用。 這是怎么回事?
AA <- 1:rowlength
BB <- 1:ncol(Nmatrix)
for(i in AA){
for(j in BB){
if (is.finite(TMatrix[i,j])==FALSE){
TNS <- matrix(data=NA,nrow=1,ncol=4)
TNS[1,1] <- TMatrix[i,j]
TNS[1,2] <- Nmatrix[i,j]
TNS[1,3] <- paste(rownames(TMatrix)[TMatrix[i,j]])
TNS[1,4] <- paste(colnames(TMatrix)[TMatrix[i,j]])
TMinf <- rbind(TMinf,TNS)
}
PMatrix[i,j] <- pt(TMatrix[i,j],n1+n2-2)
}
}
不知道這是怎么做的,因為您提供了零個我們需要運行的對象,但這聽起來像您想在以下示例中做些事情:
mat <- matrix(rnorm(20), nrow = 4)
mat[1, 4] <- mat[3, 2] <- NA
# [,1] [,2] [,3] [,4] [,5]
# [1,] 0.11025848 1.1021023 -0.3098129 NA -0.1358902
# [2,] 0.00351275 0.1440906 1.2141437 0.2601651 0.2504035
# [3,] -1.11565805 NA 0.1483867 -0.4102958 -0.3104319
# [4,] 0.34785864 1.5319365 1.2750632 0.1259548 -0.7594117
which(!is.finite(mat), arr.ind = TRUE)
# row col
# [1,] 3 2
# [2,] 1 4
如果您的行/列名為:
colnames(mat) <- LETTERS[1:5]
rownames(mat) <- letters[1:4]
# A B C D E
# a 0.11025848 1.1021023 -0.3098129 NA -0.1358902
# b 0.00351275 0.1440906 1.2141437 0.2601651 0.2504035
# c -1.11565805 NA 0.1483867 -0.4102958 -0.3104319
# d 0.34785864 1.5319365 1.2750632 0.1259548 -0.7594117
idx <- which(!is.finite(mat), arr.ind = TRUE)
rownames(mat)[idx[ , 'row']]
# [1] "c" "a"
colnames(mat)[idx[ , 'col']]
# [1] "B" "D"
沒關系,我知道了。 我的索引錯誤。 應該是這樣的:
AA <- 1:rowlength
BB <- 1:ncol(Nmatrix)
for(i in AA){
for(j in BB){
if (is.finite(TMatrix[i,j])==FALSE){
TNS <- matrix(data=NA,nrow=1,ncol=4)
TNS[1,1] <- TMatrix[i,j]
TNS[1,2] <- Nmatrix[i,j]
TNS[1,3] <- rownames(TMatrix)[i]
TNS[1,4] <- colnames(TMatrix)[j]
TMinf <- rbind(TMinf,TNS)
}
PMatrix[i,j] <- pt(TMatrix[i,j],n1+n2-2)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.