[R] Location attribute

(Ted Harding) Ted.Harding at manchester.ac.uk
Sun May 16 10:42:32 CEST 2010


On 16-May-10 06:11:52, Agustín Muñoz "M. (AMFOR) wrote:
> hi everybody, a question, as I can know the location (number) of an
> attribute with its name.
> 
> Ej.
> 
> X1  X2  X3  X4  X5  X6
> 1   3   5   2   1   7
> 6   7   4   5   2   9
> 
> as I can know that the attribute "X4" is in position 4
> 
> I hope you can help me
> 
> from already thank you very much to all
> Agustín

You can use the function colnames(), with either a matrix or a
dataframe, to extract (or set) the column names:

  X <- matrix(c( 1,3,5,2,1,7,6,7,4,5,2,9), byrow=TRUE,nrow=2)
  colnames(X) <- c("X1","X2","X3","X4","X5","X6")
  X
  #      X1 X2 X3 X4 X5 X6
  # [1,]  1  3  5  2  1  7
  # [2,]  6  7  4  5  2  9
  colnames(X)
  # [1] "X1" "X2" "X3" "X4" "X5" "X6"
  which(colnames(X)=="X4")
  # [1] 4

  X <- data.frame(X1=c(1,6),X2=c(3,7),X3=c(5,4),
                  X4=c(2,5),X5=c(1,2),X6=c(7,9))
  X
  #   X1 X2 X3 X4 X5 X6
  # 1  1  3  5  2  1  7
  # 2  6  7  4  5  2  9
  colnames(X)
  # [1] "X1" "X2" "X3" "X4" "X5" "X6"
  which(colnames(X)=="X4")
  # [1] 4

So, in either case,

  which(colnames(X)=="X4")

will give the result you want.

Hoping this helps,
Ted.

--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 16-May-10                                       Time: 09:42:28
------------------------------ XFMail ------------------------------



More information about the R-help mailing list