[英]In R, with a list of matrices, how can I quickly find the difference between the first and second row in each matrix in the list?
[英]How can I check if a matrix is an element of a list of matrices? in R
我對R中的編程很陌生。
我有一個數字矩陣mat
,以及矩陣列表matlist
。 我想檢查矩陣mat
是否與matlist
任何元素匹配(即,相同)。 我嘗試了%in%
方法,但這並沒有給我希望的輸出。
這就像我的代碼。
mat <- rbind(c(0,1),
c(1,0))
mat2 <- rbind(c(1,1),
c(1,0))
matlist <- vector(mode="list", 2)
matlist[[1]] <- mat
matlist[[2]] <- mat2
如果我然后mat %in% matlist
嘗試mat %in% matlist
我得到: FALSE FALSE FALSE FALSE
我正在尋找一個這樣的表達式,它將評估為TRUE
。
這看起來應該很簡單,但我找不到答案!
你可以嘗試類似的東西:
sapply(matlist,function(x) identical(x,mat))
,或者@jbaums提到: sapply(matlist,identical,mat)
或者自己構建一個自定義函數來檢查任何矩陣列表中的任何矩陣:
matrix_is_in <- function(my_mat, my_mat_list) {
sapply(my_matlist, function(x) identical(x, my_mat))
}
然后嘗試一下:
matrix_is_in(mat,matlist)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.