0

Following this Stackoverflow question about how to get the diagonal vectors from a matrix (Get all diagonal vectors from matrix) I was stuck when trying to save one of the elements.

A <- matrix(1:16, 4)
d <- row(A) - col(A)
d.chem <- split(A, d)
d.chem 
# $`-3`
# [1] 13
# 
# $`-2`
# [1]  9 14
# 
# $`-1`
# [1]  5 10 15
# 
# $`0`
# [1]  1  6 11 16
# 
# $`1`
# [1]  2  7 12
# 
# $`2`
# [1] 3 8
# 
# $`3`
# [1] 4

I would like to save just this element: $-1. How can I do it? I tried the following but I got an error message:

    lapply(d.chem, '[[', 3)
#Error in FUN(X[[i]], ...) : subscript out of bounds
    unlist(lapply(d.chem, '[[', 3))
#Error in FUN(X[[i]], ...) : subscript out of bounds
Community
  • 1
  • 1
A. Idigoras
  • 57
  • 1
  • 11

2 Answers2

2

You can use:

d.chem$`-1`

Consider using `` signs to access "-1" named member of list.

Sabri Karagönen
  • 2,212
  • 1
  • 14
  • 28
0

You can also access the element via the index d.chem[3] as well

amonk
  • 1,769
  • 2
  • 18
  • 27