r - How do I replace multiple column names with substring -
i want edit multiple column names substring(). code wrote isn't working.
weirdly enough 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 new column names:
newcolnames <- substring(names(forcesdf[,c(5:20)]), 1, 4) oldcolnames <- newcolnames
results in excually want:
> oldcolnames [1] "2000" "2001" "2002" "2003" "2004" "2005" "2006" "2007" "2008" "2009" "2010" "2011" "2012" "2013" "2014" "2015"
of course, want change column names in dataframe initially, wrote following code 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]"
test this
names(forcesdf)[5:20] <- substring(names(forcesdf[,c(5:20)]), 1, 4)
Comments
Post a Comment