Pergunta

Assume I have a list of variables (class:xts) in .GlobalEnv identified as follows:

ABC.xyz
DEF.xyz
GHI.xyz

These variables are generated via a function.

At present, the "column headers" in each variable are nonsense from the output of the original function.

I would like to rename the columns in each of these variables to the first three letters of the variable name, followed by a generic suffix; say:

".XXX"

I have tried to write a quick loop that uses the function dimnames(x) to achieve this is as follows:

rename.list <- ls(pattern="*.xyz",envir=.GlobalEnv)


for (i in 1:length(rename.list)){

    dimnames(rename.list[i]) <-list(
        NULL,
        c(paste(substr(rename.list[i],0,3),".XXX",sep="")))
}

This produces the error:

error in dimnames(rename.list[i]) <- list(NULL, c(paste(substr(rename.list[i], 0, 3), : 'dimnames' applied to non-array

I can see why this error occurs (using dimnames on rename.list is calling the name itself rather than the xts object), but not sure how to get around this. Tried using get etc.

Details:

R 2.13 Win 7 Package 'xts' loaded.

Many thanks in advance for any help (or suggestions to avoid the loop at all!)

Foi útil?

Solução

You can try assign:

tmp <- get(rename.list[i])
names(tmp) <- ...
assign(rename.list[i], tmp, envir=.GlobalEnv)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top