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.
Just set drop=FALSE
as in:
> y = x[1,, drop=FALSE]
> y
a b
[1,] 1 3
How about
x[1,,drop=FALSE]
a b
[1,] 1 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With