enfascination
enfascination

Reputation: 1036

prevent conversion of one-column matrix to numeric?

Here is my problem:

gg <- matrix(0,4,4)
class(gg)
class(gg[,1])

R is being a little too helpful here; I'd prefer that the one-column matrix stayed a matrix. This works, but it gets expensive:

class(t(t(gg[,1])))

And this works, but it seems like it shouldn't have to be necessary:

class(matrix(gg[,1], ncol=1))

Can you recommend a nice alternative, as brainless, effortless, and costless as possible?

Upvotes: 1

Views: 101

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193527

Use the argument drop = FALSE:

gg[, 1, drop = FALSE]
#      [,1]
# [1,]    0
# [2,]    0
# [3,]    0
# [4,]    0

class(gg[,1, drop = FALSE])
# [1] "matrix"

Upvotes: 4

Related Questions