[R] Need to abstract changing name of column within loop
jctoll
jctoll at gmail.com
Thu Mar 17 00:58:31 CET 2011
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"
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