4

I am trying to get a particular diagonal from my data. This is my code :

a2008=c(30,50,65)
a2009=c(40,90,NA)
a2010=c(55,NA,NA)

mydata=rbind(a2008,a2009,a2010)
mydata
      [,1] [,2] [,3]
a2008   30   50   65
a2009   40   90   NA
a2010   55   NA   NA

how can we get the diagonal 65, 90, 55 ?

I already used the diag function but i got 30, 90, NA.

Some help would be appreciated

John john
  • 437
  • 3
  • 13

5 Answers5

4

To get the main anti-diagonal, you can do this. (rev to get stated order)

mydata[row(mydata) + col(mydata) == ncol(mydata) + 1]

You can get the diagonal below that with

mydata[row(mydata) + col(mydata) == ncol(mydata) + 2]

and so on

IceCreamToucan
  • 28,083
  • 2
  • 22
  • 38
3

you can try to get the antidiagonal by

diag(mydata[,nrow(mydata):1])
[1] 65 90 55

or

diag(as.matrix(rev(as.data.frame(mydata)))) 
Roman
  • 17,008
  • 3
  • 36
  • 49
2

You can get that diagonal by flipping your matrix before calling diag:

diag(mydata[ , 3:1]) # [1] 65 90 55

Doing mydata[ , 3:1] is indexing the columns of your matrix in reverse order.

C. Braun
  • 5,061
  • 19
  • 47
2

That's a matrix, not a data frame. Which is good! Diagonals of data frames don't make much sense. I would do it like this:

mydata[cbind(1:3, 3:1)]
# [1] 65 90 55

You can use a matrix to index a matrix, this is saying you want the values from rows 1, 2, 3 and columns 3, 2, 1.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
1

You can achieve this by first flipping the matrix and them finding the diagonal. That is

diag(apply(mydata, 1, rev))

I hope this helps!

smanski
  • 541
  • 2
  • 7