Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append a string to subset of variable names in R?

Tags:

r

rename

I am trying to alter a select few of my variable names in a data frame. How can I do this without typing each of the old names and each of the new names? I thought the code below might work but it hasn't. I am trying to append "Econ" to each of the existing names identified in the data frame.

    names(wb.misc)[3,13,14,20,22,47,61,62,64,68,73] <- 
         paste("Econ", names(wb.misc)[3,13,14,20,22,47,61,62,64,68,73], sep = "-")
like image 892
DBK Avatar asked Feb 23 '13 22:02

DBK


People also ask

How do I pass a string to a variable name in R?

We can assign character string to variable name by using assign() function. We simply have to pass the name of the variable and the value to the function. Parameter: variable_name is the name of the value.

How do I combine two variables in R?

How do I concatenate two columns in R? To concatenate two columns you can use the <code>paste()</code> function. For example, if you want to combine the two columns A and B in the dataframe df you can use the following code: <code>df['AB'] <- paste(df$A, df$B)</code>.


2 Answers

You need to put c() around the indices

 names(wb.misc)[c(3,13,14,20,22,47,61,62,64,68,73)] = paste("Econ", names(wb.misc)[c(3,13,14,20,22,47,61,62,64,68,73)], sep = "-")
like image 111
adibender Avatar answered Sep 29 '22 08:09

adibender


One way to efficiently get the variable names is to use dput(names(df)) where df is your data.frame.

For example, using the built-in dataset airquality, you can do the following

dput(names(airquality))

Which gives you:

c("Ozone", "Solar.R", "Wind", "Temp", "Month", "Day")

You can then edit to extract the columns you want without having to type them from scratch. E.g., say you want to rename the following three variables, you could use rename.vars in gdata.

vars <- c("Ozone",  "Wind", "Temp")
library(gdata)
rename.vars(airquality, from=vars, to=paste0("Econ", vars))

Using actual variable names will also generally make your code more reliable.

like image 31
Jeromy Anglim Avatar answered Sep 29 '22 07:09

Jeromy Anglim