0

I want to edit multiple column names with the substring(). Only the code I wrote isn't working.

Weirdly enough the following code works. Old column names:

oldColNames <- names(forcesdf[,c(5:20)])

results in:

> names(forcesdf[,c(5:20)])
[1] "2000 [YR2000]" "2001 [YR2001]" "2002 [YR2002]" "2003 [YR2003]" "2004 [YR2004]" "2005 [YR2005]" "2006 [YR2006]"
[8] "2007 [YR2007]" "2008 [YR2008]" "2009 [YR2009]" "2010 [YR2010]" "2011 [YR2011]" "2012 [YR2012]" "2013 [YR2013]"
[15] "2014 [YR2014]" "2015 [YR2015]"

And the new column names:

newColNames <- substring(names(forcesdf[,c(5:20)]), 1, 4)
oldColNames <- newColNames

Results in what I excually want:

> oldColNames
[1] "2000" "2001" "2002" "2003" "2004" "2005" "2006" "2007" "2008" "2009" "2010" "2011" "2012" "2013" "2014" "2015"

Of course, I want to change the column names in my dataframe so initially, I wrote the following code but the colnames didn't change.

names(forcesdf[,c(5:20)]) <- substring(names(forcesdf[,c(5:20)]), 1, 4)

> names(forcesdf[,c(5:20)])
[1] "2000 [YR2000]" "2001 [YR2001]" "2002 [YR2002]" "2003 [YR2003]" "2004 [YR2004]" "2005 [YR2005]" "2006 [YR2006]"
[8] "2007 [YR2007]" "2008 [YR2008]" "2009 [YR2009]" "2010 [YR2010]" "2011 [YR2011]" "2012 [YR2012]" "2013 [YR2013]"
[15] "2014 [YR2014]" "2015 [YR2015]"

2 Answers 2

1

Test this

names(forcesdf)[5:20] <- substring(names(forcesdf[,c(5:20)]), 1, 4)
Sign up to request clarification or add additional context in comments.

Comments

0

You can change them if you do:

names(forcesdf)[5:20] <- substring(names(forcesdf)[5:20], 1, 4)

I think the key is that in your code you are subsetting the column names but not referencing to them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.