如何用子串

时间:2017-08-15 11:45:05

标签: r substring multiple-columns rename

我想用substring()编辑多个列名。只有我写的代码不起作用。

奇怪的是,以下代码有效。 旧列名:

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

结果:

> 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]"

新列名称:

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

结果出乎我想要的那样:

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

当然,我想更改数据框中的列名,所以最初,我编写了以下代码,但代码名没有改变。

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 个答案:

答案 0 :(得分:1)

测试此

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

答案 1 :(得分:0)

如果您这样做,可以更改它们:

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

我认为关键是你的代码中你是列名列的子集,但没有引用它们。