Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add column inside named matrix

Tags:

r

matrix

Suppose I have the following matrix:

m <- matrix(1:12, nrow = 3, dimnames = list(c("a", "b", "c"), c("w", "x", "y", "z")))
#   w x y  z
# a 1 4 7 10
# b 2 5 8 11
# c 3 6 9 12

How can I add a column with the values c(13, 14, 15) between column x and y without knowing where x and y are?

Using number ranges I know how to do this using cbind.

cbind(m[,1:2], c(13, 14, 15), m[,3:4])
#   w x    y  z
# a 1 4 13 7 10
# b 2 5 14 8 11
# c 3 6 15 9 12

For named columns, it'd be neat if I could supply the column ranges with m[,:"x"] and m[,"y":] of some sort, but unfortunately that doesn't work.

Additionally, if possible, giving that column its own header name during the insertion process would be nice.

EDIT: I should have specified that x and y always are in order, so adding the column after x would have been enough. Thanks for the more general answers as well!

like image 668
Felix Jassler Avatar asked Jan 25 '26 12:01

Felix Jassler


2 Answers

When you can not assume that x comes before y and there is no need that they are following each without a gap you can try:

i <- seq_len(min(match(c("x", "y"), colnames(m))))
cbind(m[,i], v=c(13, 14, 15), m[,-i])
#  w x  v y  z
#a 1 4 13 7 10
#b 2 5 14 8 11
#c 3 6 15 9 12

In case they are ordered, that it will be enough to put it after x like:

i <- seq_len(match("x", colnames(m)))
cbind(m[,i], v=c(13, 14, 15), m[,-i])
like image 178
GKi Avatar answered Jan 27 '26 02:01

GKi


you may found the columns positions by names and insert the new column properly:

x_pos <- which(colnames(m) == "x")
y_pos <- which(colnames(m) == "y")
m <- cbind(m[,1:x_pos], new=c(13, 14, 15), m[,y_pos:ncol(m)])
like image 23
Ivalbert Pereira Avatar answered Jan 27 '26 02:01

Ivalbert Pereira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!