3

If I make a matrix like so;

m<-matrix(1,dimnames=list('row','column'))
    column
row      1

I can add a new row like so with rbind

m<-rbind(m,row2=2)
     column 
row       1 
row2      2

But... if I have a string variable like

tag<-"row3"

Why can't I used rbind as

m<-rbind(m,tag=3)

where row3 should be and not tag as

     column
row       1
row2      2
tag       3

but want

     column
row       1
row2      2
row3      3
0

3 Answers 3

4

You could just use rbind without naming the new row, and then use rownames to name that row:

m <- rbind(m,3)
rownames(m)[3]<-tag

Some benchmarking between this and @agstudy's solution:

m <- matrix(1,dimnames=list('row','column'))
m <- rbind(m,row2=2)
tag <- "row3"

fn1<-function(m,tag){
  m <- rbind(m,matrix(3,dimnames=list(tag,'column')))
  m
}

fn2<-function(m,tag){
  m <- rbind(m,3)
  rownames(m)[3]<-tag
  m
}
library(microbenchmark)
microbenchmark(fn1(m,tag),fn2(m,tag))
Unit: microseconds
        expr    min     lq median     uq    max neval
 fn1(m, tag)  4.665  5.598  6.065  6.532 15.862   100
 fn2(m, tag) 11.663 13.062 13.063 13.530 48.517   100
Sign up to request clarification or add additional context in comments.

1 Comment

I would also do this my way, although your method seems to be slightly faster: microbenchmark gives 6 microseconds versus 13 ;)
3

you can do this , by creating a matrix with right dimnames

m <- matrix(1,dimnames=list('row','column'))
m <- rbind(m,row2=2)
tag <- "row3"
m <- rbind(m,matrix(3,dimnames=list(tag,'column')))

m
     column
row       1
row2      2
row3      3

4 Comments

I think he wants the rowname as row3 not tag, and 3 as value.
@Hemmo Thanks. I change my answer.
@Hemmo maybe nice but I find it tricky! actually I would use your solution in the comment.
Ags and Hem, thanks for your answers, both work and save me time
2

Since substitute() does not process function arguments, the only way to emulate a dynamic variable name in this case would be eval(parse(...)):

> m <- eval(parse(text=paste("rbind(m,",tag,"=3)")))
> m
     column
row       1
row2      2
row3      3

It is freaky, and I would not recommend it, but I post it for completeness.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.