Reputation: 1816
I am currently trying to duplicate the diag()
function in R to get a better understanding. Unfortunately, my solution is only useful for symmetric matrices.
diagnew <- function(x){
k <- c()
for(i in 1:nrow(x)){
k[i] <- x[i,i]
}
return(k)
}
I would be grateful for any tips that allow me to generalize my function.
Upvotes: 3
Views: 123
Reputation: 76605
The error comes from looping pass min(nrow, ncol)
.
diagnew <- function(x){
n <- min(nrow(x), ncol(x))
k <- vector(class(x[1,1]), n)
for(i in seq.int(n)){
k[i] <- x[i,i]
}
k
}
mat <- matrix(1:10, 5)
diag(mat)
diagnew(mat)
identical(diag(mat), diagnew(mat))
#[1] TRUE
Upvotes: 3