Simon
Simon

Reputation: 349

Write as many 1 in vector as there are rows in matrix

I have a matrix

mat = matrix(c(1,2,3,4), ncol = 2)

and I wish to create the vector

vec = c(1,1)

which contains as many 1 that there are lines in the matrix.

How to do it fast?

Upvotes: 1

Views: 37

Answers (2)

MichaelChirico
MichaelChirico

Reputation: 34703

On the suspicion that you might be trying to creating the column vector of 1s for the design matrix of a linear regression (i.e. the "dummy" data corresponding to the intercept term), you might also benefit from knowing this alternative:

model.matrix( ~ 1, data.frame(mat))

(LHS of the formula is irrelevant so it's left empty; 1 represents the constant term)

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388982

If by lines you mean rows you can use rep

rep(1, nrow(mat))
#[1] 1 1

Upvotes: 1

Related Questions