[英]In R, is there any native function to get a row or column of a matrix, depending on the parameter?
我目前正在使用此實現:
getVal = function(i, x, margin) {
rst = ifelse(margin==1, x[i, ], x[, i])
}
即返回x的第i行或列,具體取決於邊距的值。
===更新===
剛意識到我在這里使用ifelse(x,y,z)
語句是錯誤的,因為它返回的值與其第一個參數的長度相同。 我的getVal
實現應具有:
...
rst = if (margin == 1) x[i, ] else x[, i]
...
abind::asub()
所做的事情非常類似於您要嘗試做的事情(並且很好地推廣到了高維數組)。 它的idx
和dims
參數分別對應於i
和margin
參數。
library(abind)
(m <- matrix(1:6, ncol=2))
# [,1] [,2]
# [1,] 1 4
# [2,] 2 5
# [3,] 3 6
asub(x = m, idx = 2, dims = 1) # Extract 2nd row
# [1] 2 5
asub(x = m, idx = 2, dims = 2) # Extract 2nd column
# [1] 4 5 6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.