如何重命名 R 对象? [英] How do I rename an R object?

查看:71
本文介绍了如何重命名 R 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 quantmod 包从雅虎导入金融系列数据.

I'm using the quantmod package to import financial series data from Yahoo.

library(quantmod)
getSymbols("^GSPC")
[1] "GSPC"

我想将对象GSPC"的名称更改为SPX".我试过 reshape 包中的 rename 函数,但它只改变了变量名.GSPC"对象具有向量 GSPC.Open、GSPC.High 等.我希望将GSPC"重命名为SPX"以将 GSPC.Open 更改为 SPX.Open 等.

I'd like to change the name of object "GSPC" to "SPX". I've tried the rename function in the reshape package, but it only changes the variable names. The "GSPC" object has vectors GSPC.Open, GSPC.High, etc. I'd like my renaming of "GSPC" to "SPX" to also change GSPC.Open to SPX.Open and so on.

推荐答案

重命名对象及其中的列名是一个两步过程:

Renaming an object and the colnames within it is a two step process:

SPY <- GSPC # assign the object to the new name (creates a copy)
colnames(SPY) <- gsub("GSPC", "SPY", colnames(SPY)) # rename the column names

否则,getSymbols 函数允许您自动分配,在这种情况下您可以跳过第一步(您仍然需要重命名列).

Otherwise, the getSymbols function allows you to not auto assign, in which case you could skip the first step (you will still need to rename the columns).

SPY <- getSymbols("^GSPC", auto.assign=FALSE)

<小时>

@backlin 的评论

R 采用所谓的惰性求值.这样做的结果是,当您复制"SPY <- GSPC 时,您实际上并未在内存中为 SPY 分配新空间.R 知道这些对象是相同的,并且只有在其中一个被修改时才会在内存中创建一个新副本(当它们不再相同时,例如当您更改列名在下一行).所以通过这样做

R employs so-called lazy evaluation. An effect of that is that when you "copy" SPY <- GSPC you do not actually allocate new space in the memory for SPY. R knows the objects are identical and only makes a new copy in the memory if one of them is modified (i.e. when they are no longer the identical, e.g. when you change the column names on the following line). So by doing

SPY <- GSPC
rm(GSPC)
colnames(SPY) <- gsub("GSPC", "SPY", colnames(SPY))

你从来没有真正复制GSPC,而只是给它一个新名字(SPY)然后告诉R忘记名字(GSPC).当您随后更改列名称时,您不需要创建 SPY 的新副本,因为 GSPC 不再存在,这意味着您已经真正重命名了对象,而无需创建中间副本.

you never really copy GSPC but merely give it a new name (SPY) and then tell R to forget the first name (GSPC). When you then change the column names you do not need to create a new copy of SPY since GSPC no longer exists, meaning you have truly renamed the object without creating intermediate copies.

这篇关于如何重命名 R 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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