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

风格不统一 提交于 2019-12-10 20:33:31

问题


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 = "-")

回答1:


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 = "-")



回答2:


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.



来源:https://stackoverflow.com/questions/15046296/how-to-append-a-string-to-subset-of-variable-names-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!