In R: Naming elements of a vector as, e.g., c(name1=x1,name2=x2) without elements' prior names interfering

47 Views Asked by At

When I create vectors using output from previous functions, I like to give the elements name. For example:

x=rnorm(100)
z=sample(c(0,1),100,replace=TRUE)
y=.5*x+.5*x^2+z+rnorm(100)

linMod=lm(y~x+z)
quadMod=lm(y~poly(x,2)+z)

Zcoefs=c(lin=coef(linMod)['z'],quad=coef(quadMod)['z'])

What I would like is this:

> names(Zcoefs)
[1] "lin"  "quad"

But what I get instead is this:

> names(Zcoefs)
[1] "lin.z"  "quad.z"

with the ".z" carried over from the output of coef().

Two solutions I know about both have problems. First, setNames():

Zcoefs=setNames(c(coef(linMod)['z'],coef(quadMod)['z']),c('lin','quad'))

The problem is that in order to do this you need to keep track (in your head!) of the order of objects in the vector and the order of the names, which seems like it could easily cause bugs.

The other solution uses unname(), which is super clunky:

Zcoefs=c(lin=unname(coef(linMod)['z']),quad=unname(coef(quadMod)['z']))

Does anyone have any suggestions for a better way?

1

There are 1 best solutions below

0
Waldi On

You could use double brackets [[]] which give direct access to the elements of the vector without their names:

Zcoefs=c(lin=coef(linMod)[['z']],quad=coef(quadMod)[['z']])

names(Zcoefs)
#[1] "lin"  "quad"