[R] Need to abstract changing name of column within loop

jctoll jctoll at gmail.com
Thu Mar 17 02:43:15 CET 2011


On Wed, Mar 16, 2011 at 8:20 PM, David Winsemius <dwinsemius at comcast.net> wrote:
>
> On Mar 16, 2011, at 7:58 PM, jctoll wrote:
>
>> Hi,
>>
>> I'm struggling to figure out the way to change the name of a column
>> from within a loop.  The problem is I can't refer to the object by its
>> actual variable name, since that will change each time through the
>> loop.  My xts object is A.
>>
>>> head(A)
>>
>>          A.Open A.High A.Low A.Close A.Volume A.Adjusted A.Adjusted.1
>> 2007-01-03  34.99  35.48 34.05   34.30  2574600      34.30  11867800000
>> 2007-01-04  34.30  34.60 33.46   34.41  2073700      34.41  11905860000
>> 2007-01-05  34.30  34.40 34.00   34.09  2676600      34.09  11795140000
>> 2007-01-08  33.98  34.08 33.68   33.97  1557200      33.97  11753620000
>> 2007-01-09  34.08  34.32 33.63   34.01  1386200      34.01  11767460000
>> 2007-01-10  34.04  34.04 33.37   33.70  2157400      33.70  11660200000
>>
>> It's column names are:
>>>
>>> colnames(A)
>>
>> [1] "A.Open"       "A.High"       "A.Low"        "A.Close"
>> "A.Volume"     "A.Adjusted"   "A.Adjusted.1"
>>
>> I want to change the 7th column name:
>>>
>>> colnames(A)[7]
>>
>> [1] "A.Adjusted.1"
>>
>> I need to do that through a reference to i:
>>>
>>> i
>>
>> [1] "A"
>>
>
> It's not pretty and there may be a more direct way:
>> a
>      [,1] [,2]
> [1,] 1e+20 1000
> [2,] 1e+02 1000
>> b <- "a"
>> assign("tmp", eval(parse(text=b)))
>> tmp
>      [,1] [,2]
> [1,] 1e+20 1000
> [2,] 1e+02 1000
>> colnames(tmp) <- c("one","two")
>> assign( b, tmp)
>> a
>       one  two
> [1,] 1e+20 1000
> [2,] 1e+02 1000
>
>
> Trying to short circuit the process without an intermediate temporary
> structure fails:
>> colnames(eval(parse(text=b)) )<- c("two", "three")
> Error in parse(`*tmp*`) : EOF whilst reading MBCS char at line 1
> --
> David


Thank you.  This seems to work, but as you observed it's not exactly elegant.

Thanks,

James




>
>> This works:
>>>
>>> colnames(get(i))[7]
>>
>> [1] "A.Adjusted.1"
>>
>> And this is what I want to change the column name to:
>>>
>>> paste(i, ".MarketCap", sep = "")
>>
>> [1] "A.MarketCap"
>>
>> But how do I make the assignment?  This clearly doesn't work:
>>
>>> colnames(get(i))[7] <-  paste(i, ".MarketCap", sep = "")
>>
>> Error in colnames(get(i))[7] <- paste(i, ".MarketCap", sep = "") :
>>  could not find function "get<-"
>>
>> Nor does this (it creates a new object "A.Adjusted.1" with a value of
>> "A.MarketCap") :
>>
>> assign(colnames(get(i))[7], paste(i, ".MarketCap", sep = ""))
>>
>> How can I change the name of that column within my big loop?  Any
>> ideas?  Thanks!
>>
>> Best regards,
>>
>>
>> James
>>



More information about the R-help mailing list