簡體   English   中英

識別滿足條件的行並存儲在矩陣中

[英]Identify rows that meet condition and store in matrix

我需要確定滿足條件的矩陣行。 我將問題設置如下。 總體而言,目標是確定1)特定列中的前兩個條目是什么,以及2)這些列對應的行。 然后,我想將各個行存儲在2xn矩陣中。

Mat1 <- data.frame(matrix(nrow = 10, ncol =250, data = rnorm(250,0,1)))
seq1 <- seq(1, 247,3)

 Mat1[,1:4]
            X1         X2          X3           X4
1   0.39560216 -1.2391890  1.00771944 -0.225181006
2  -0.92136335 -0.5042209  0.51758214 -0.008936688
3  -0.67657261  1.3167817 -0.22997139 -1.478361654
4  -1.94389531  0.7944302 -0.16763378 -1.847748926
5   0.11998316  0.4850342 -2.47604164 -0.846030811
6   1.26607727  2.3710318 -0.60115423  1.255747735
7  -1.09798680 -0.2817050  0.03150861 -1.350501958
8   0.43790646  0.1989955  1.22612459  0.323815132
9   0.61639304  0.8102352 -0.69921481  0.118795023
10  0.01786964 -0.1222586 -1.50414879  0.649616182


因此,在第1列(seq1 [1])中,前兩個條目是1.266077和0.616393。 這些對應於第6行和第5行。在第4列中,前兩個條目是1.2557477和0.6496162。 這些對應於第6行和第10行。我想對seq1中的所有元素重復此過程。 我想將輸出存儲在2 x length(seq1)的矩陣中(例如Output)。 第一行應對應於最大值,第二行應為第二最大值。

您可以嘗試這樣的事情:

set.seed(2) # "fix" your random numbers due reproducibility
Mat1 <- data.frame(matrix(nrow = 10, ncol =250, data = rnorm(250,0,1)))
seq1 <- seq(1, 247,3)

# select the interesting columns
Mat2 <- Mat1[,c(seq1)]

# create a matrix with the row names of the top 2 values for each interesting column
dat <- sapply(Mat2, function(x) head(row.names(Mat2)[order(x, decreasing = TRUE)], 2)   
class(dat)
[1] "matrix"

dat[,1:4]
     X1  X4  X7  X10
[1,] "9" "3" "2" "7"
[2,] "3" "1" "5" "2"

您可以通過sapplyorder以及subsetting[1:2] )獲得索引:

tt <- sapply(Mat1[,seq1], function(x) order(x, decreasing = TRUE)[1:2])
#or
tt <- sapply(Mat1[,seq1], order, decreasing = TRUE)[1:2,]

以及帶有以下值的值:

matrix(Mat1[matrix(c(tt, rep(seq1, each=2)), ncol = 2)], 2)
#or
sapply(Mat1[,seq1], function(x) sort(x, decreasing = TRUE)[1:2])

您可以使用以下方法獲得所有其他行但不是兩個最大行的索引:

sapply(Mat1[,seq1], order, decreasing = TRUE)[-(1:2),]

你可以做:

M <- read.table(header=TRUE, text=
"X1         X2          X3           X4
0.39560216 -1.2391890  1.00771944 -0.225181006
-0.92136335 -0.5042209  0.51758214 -0.008936688
-0.67657261  1.3167817 -0.22997139 -1.478361654
-1.94389531  0.7944302 -0.16763378 -1.847748926
0.11998316  0.4850342 -2.47604164 -0.846030811
1.26607727  2.3710318 -0.60115423  1.255747735
-1.09798680 -0.2817050  0.03150861 -1.350501958
0.43790646  0.1989955  1.22612459  0.323815132
0.61639304  0.8102352 -0.69921481  0.118795023
0.01786964 -0.1222586 -1.50414879  0.649616182")

M <- as.matrix(M)
M

my12 <- function(x) { m <- which.max(x); x[m] <- -Inf; c(m, which.max(x)) };
apply(M, 2, my12)
# > apply(M, 2, my12)
#      X1 X2 X3 X4
# [1,]  6  6  8  6
# [2,]  9  3  1 10

要獲取值(例如最大值):

I <- apply(M, 2, my12)
M[cbind(I[1,], 1:ncol(M))]

如果M是一個數據幀,則可以執行sapply(M, my12) ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM