Search code examples
rvariable-namesgrepl

R : Changing variable names with a for(); grepl() and colnames()


Im trying to make a data panel and in the way i have to rename some columns in order to apply rbind() and then run some statistics.

i have multiple objects like this:

data22

1. year -- id-----22.Letters.spendingXX -----22.Letters.IncomeXX 
2. 1999 -- 22 ------ 21 ---------------------------- 52
3. 2000 -- 22 ------ 25----------------------------- 31           
4. 2002 -- 22------- 54 ---------------------------- 98
5. 2001 -- 22  ----- 43 -----------------------------12

and;

data3

1. year -- id---  3.OtherLetters.IncomeXX --- 3.other.Letters.spending1234
2. 1999 -- 3---------   23------------------------  45
3. 2000 -- 3---------   25  ------------------------65
4. 2001 -- 3---------   31 ------------------------ 34
5. 2002 -- 3---------   54   -----------------------12

and so on,

i want to change the column names according to the variable it is (because the are unsorted i can't do it by the normal and easy procedure), so for example i tried to use:

try<-grepl("spending",colnames(data22))
colnames(data22[try])<-c("Spending")

and with this idea i was planning to apply it in a for (), but its nos working even without the for()

Thanks for your help JD


Solution

  • I think you should try colnames(data22)[try] <-c("Spending") instead of colnames(data22[try])<-c("Spending")

    Lise