Wilduck
Wilduck

Reputation: 14116

R: Changing the names in a named vector

R's named vectors are incredibly handy, however, I want to combine two vectors which contain the estimates of coefficients and the standard errors for those estimates, and both vectors have the same names:

> coefficients_estimated
     y0         Xit  (Intercept) 
    1.1         2.2          3.3 

> ses_estimated
     y0         Xit  (Intercept) 
    .04         .11         .007

This would be easy to solve if I knew what order the elements were in for sure, but this isn't guaranteed in my script, so I can't simply do names(ses_estimated) <- whatever. All I want to do is add either "coef" or "se" to the end of each name, and to do this, I've come up with what I think is a pretty ugly hack:

names(coefficients_estimated) <- sapply(names(coefficients_estimated),
                                        function(name)return(paste(name,"coef",sep=""))
                                        )
names(ses_estimated) <- sapply(names(ses_estimated),
                               function(name)return(paste(name,"se",sep=""))
                               )

Is there an idomatic way to do this? Or am I going to have to stick with what I've written?

Upvotes: 1

Views: 12940

Answers (3)

David F
David F

Reputation: 1265

setNames is helpful here:

# Make fake data for test:
namedData <- function(x) setNames(x, c("y0", "Xit", "(Intercept)"))

coefficients_estimated <- namedData(c(1.1, 2.2, 3.3))
ses_estimated <- namedData(c(.04, .11, .007))

# Do it:
withNameSuffix <- function(obj, suffix) setNames(obj, paste(names(obj), suffix, sep=""))
combined <- c(withNameSuffix(coefficients_estimated, "coef"),
              withNameSuffix(ses_estimated, "se"))

Upvotes: 2

Wojciech Sobala
Wojciech Sobala

Reputation: 7561

coef_ses_estimated <- c(coefficients_estimated,ses_estimated)
names(coef_ses_estimated) <- as.vector(outer(names(coefficients_estimated),
                                             c("coef","se"),paste,sep="_"))

Upvotes: 1

Noah
Noah

Reputation: 2624

Assuming you're combining the vectors using c(), I don't believe there's a "pure" way to do this.

In your code above, you don't even need to use sapply. Just paste(names(coefficients_estimated), "coef", sep="") will get you the same thing. You can get a little simpler still by applying the names to the combined vector vs. separately.

If these were data frames, the suffixes argument would be exactly what you want.

Upvotes: 2

Related Questions