Fixing dimnames(x) of xts objects in R via loop

坚强是说给别人听的谎言 提交于 2019-12-12 20:28:14

问题


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!)


回答1:


You can try assign:

tmp <- get(rename.list[i])
names(tmp) <- ...
assign(rename.list[i], tmp, envir=.GlobalEnv)


来源:https://stackoverflow.com/questions/8815075/fixing-dimnamesx-of-xts-objects-in-r-via-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!