Constantly a subset of a matrix in a vector and avoiding colnames?

I would like to know if there is an R syntax for extracting a column from a matrix and always does not have a name attribute for the returned vector (I want to rely on this behavior).

My problem is the following mismatch:

  • when the matrix has more than one row, and I do myMatrix[, 1]I get the first column myMatrixwithout a name attribute. This is what I want.
  • when the matrix has exactly one row , and I do myMatrix[, 1], I will get the first column myMatrix , but it has the first colname as its name .

I would like to be able to do myMatrix[, 1]and consistently receive something with an unnamed name .

An example demonstrating this:

# make a matrix with more than one row,
x <- matrix(1:2, nrow=2)
colnames(x) <- 'foo'
#      foo
# [1,]   1
# [2,]   2

# extract first column. Note no 'foo' name is attached.
x[, 1]
# [1] 1 2

# now suppose x has just one row (and is a matrix)
x <- x[1, , drop=F]
# extract first column
x[, 1]
# foo    # <-- we keep the name!!
#   1

[ (?'[') , - (, ?! ?!):

, , , "x , ( ) .

, x[, 1] , , x - ?

unname(x[, 1]) - [ drop? , , " "? - , (- [, ?)

+5
1

, ( )

[ , R subset.c ~/src/main. VectorSubset. (.. , x[,1]), MatrixSubset.

VectorSubset . , . MatrixSubset, , dimnames.


, , , :

x <- matrix(1)
colnames(x) <- "foo"
x[, 1]  ## 'Normal' indexing
# foo 
#   1 
x[matrix(c(1, 1), ncol = 2)]  ## Matrix indexing
# [1] 1

1 :

xx <- matrix(1:10, nrow = 1)
colnames(xx) <- sprintf('foo%i', seq_len(ncol(xx)))
xx[, 6]  ## 'Normal' indexing
# foo6 
#    6 
xx[matrix(c(1, 6), ncol = 2)]  ## Matrix indexing
# [1] 6

> 1:

yy <- matrix(1:10, nrow = 2, dimnames = list(NULL,
  sprintf('foo%i', 1:5)))

yy[cbind(seq_len(nrow(yy)), 3)]  ## Matrix indexing
# [1] 5 6
+1
source

All Articles