2

Let's say you have a matrix defined as

m1 = matrix(
  rbind(c(12,8,9),c(4100,3600,3200)), 
  byrow=FALSE, 
  nrow=2, 
  ncol=3, 
  dimnames=list(c("Days","Amount"),c("Col1","Col2","Col3"))
  )

Which yields:

       Col1 Col2 Col3
Days     12    8    9
Amount 4100 3600 3200

And you need to show (knowing the position of the column, here 3) name of the column and its values, so that you have information about the parameters like:

  Days Amount 
     9   3200

But you also need to know the column name which carries some real information about its values (ie hotel name).

The above you could achieve with m1[, 3] like in this question, but how does one print it together with the column header? (here "Col3")

Community
  • 1
  • 1
Kamil Gosciminski
  • 16,547
  • 8
  • 49
  • 72
  • 2
    just `m1[,'Col3',drop=FALSE]` – Jaap Apr 23 '17 at 15:51
  • related: [*Extract matrix column values by matrix column name*](http://stackoverflow.com/questions/5744694/r-extract-matrix-column-values-by-matrix-column-name) – Jaap Apr 23 '17 at 15:57
  • 1
    @Jaap is it really a duplicate? I want to extract column name alongside its values. Linked question and answers do not present a solution for that. I've reviewed your linked question before posting. – Kamil Gosciminski Apr 23 '17 at 16:00
  • Yes, it is a duplicate. Please visit the linked target. It is a different than the one I posted in my comment above. – Jaap Apr 23 '17 at 16:04
  • @Jaap you're right. Question was really hard to find though due to it's title... I didn't stumble upon that while searching which either means I do not know how to name it or it isn't straightforward. – Kamil Gosciminski Apr 23 '17 at 16:06
  • @KamilG If you have any other questions, you have the option to edit the post and update it – akrun Apr 23 '17 at 16:10

2 Answers2

2

We can use drop = FALSE without converting to data.frame

m1[,3, drop = FALSE]
#        Col3
#Days      9
#Amount 3200
Jaap
  • 81,064
  • 34
  • 182
  • 193
akrun
  • 874,273
  • 37
  • 540
  • 662
1

You could coerce m1 to data.frame and slice the required column

as.data.frame(m1)[3]
#OR
as.data.frame(m1)["Col3"]
#       Col3
#Days      9
#Amount 3200
d.b
  • 32,245
  • 6
  • 36
  • 77