Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select a single row of matrix as a matrix

Tags:

r

matrix

This has been bugging me forever. Consider the following:

# Part A #
# Make a silly simple matrix with column names
x = matrix(1:4, ncol = 2)
colnames(x) = c("a","b")

# Part B #
# Pick out the first row of the matrix.  This is not a matrix, 
#   and the column names are no longer accessible by colnames()
y = x[1,]
y
is.matrix(y)
colnames(y)

# Part C #
# But here is what I want:
y = matrix(x[1,], nrow = 1, dimnames = list(c(), colnames(x)))

Is there any way to achieve Part C with fewer processing steps, or less code? It seems like there should be a command nearly as short as x[1,] that does the same thing.

like image 442
zkurtz Avatar asked Jan 12 '23 07:01

zkurtz


2 Answers

Just set drop=FALSE as in:

> y = x[1,, drop=FALSE]
> y
     a b
[1,] 1 3
like image 51
Jilber Urbina Avatar answered Jan 16 '23 01:01

Jilber Urbina


How about

x[1,,drop=FALSE]
     a b
[1,] 1 3
like image 42
Señor O Avatar answered Jan 16 '23 01:01

Señor O