0

Recently I encounter a very interesting question. I want to change the colnames of a model matrix I created.

colnames(model.matrix(~as.factor(c(rep(0,10),1:10))))<-    
as.character(sapply(0:10,function(i) paste('sample',i,sep='')))

I keep getting the err "target of assignment expands to non-language object". Finally I was able to work this out. All I do is to assign the model.matrix to a variable first and change its colnames after. Anyone can tell me why the first case didn't work out? Thanks so much

a<-model.matrix(~as.factor(c(rep(0,10),1:10))))   
colnames(a) <- as.character(sapply(0:10,function(i) paste('sample',i,sep=''))) 
yuanhangliu1
  • 157
  • 1
  • 1
  • 7
  • You can avoid using `as.character` and `sapply`, just use `paste`: `colnames(a)<- paste('sample',0:10,sep='')`, `paste` is vectorized – Jilber Urbina Jun 02 '14 at 21:47

1 Answers1

0

My guess is that one cannot modify the attributes of an anonymous object because ... it's pointless.

You can certainly create an anonymous object for the purpose of seeing the result printed to the console:

model.matrix(foo)

And you can certainly ask for the value of an attribute of an anonymous object for the purpose of seeing that value printed to the console:

colnames(model.matrix(foo))

But if you were to change the value of an attribute of an anonymous object

colnames(model.matrix(foo)) <- bar

then nothing would be printed to the console because assignment statements don't print anything. Since the anonymous object you created goes away as soon as the statement finishes executing, then there's really no reason to do this.

dg99
  • 5,456
  • 3
  • 37
  • 49