通过循环修复R中xts对象的dimnames(x) [英] Fixing dimnames(x) of xts objects in R via loop

查看:15
本文介绍了通过循环修复R中xts对象的dimnames(x)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 .GlobalEnv 中有一个变量列表 (class:xts),标识如下:

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"

我尝试编写一个使用函数dimnames(x)来实现的快速循环,如下所示:

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="")))
}

这会产生错误:

dimnames(rename.list[i]) 中的错误 <- list(NULL, c(paste(substr(rename.list[i], 0, 3), :'dimnames' 应用于非数组

我可以理解为什么会发生此错误(在 rename.list 上使用 dimnames 是调用名称本身而不是 xts 对象),但不确定如何解决此问题.尝试使用 get

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.

详情:

R 2.13赢7已加载包xts".

R 2.13 Win 7 Package 'xts' loaded.

非常感谢您提供的任何帮助(或完全避免循环的建议!)

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

推荐答案

你可以试试assign:

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

这篇关于通过循环修复R中xts对象的dimnames(x)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆