如何重命名 R 对象?

发布于 2024-08-30 12:48:04 字数 260 浏览 2 评论 0原文

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

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

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

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苍风燃霜 2024-09-06 12:48:04

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

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

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

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

来自 @backlin 的评论

R 采用所谓的惰性求值。其效果是,当您“复制”SPY <- GSPC 时,您实际上并未在内存中为 SPY 分配新空间。 R 知道对象是相同的,并且仅在其中一个对象被修改时(当它们不再相同时,例如当您更改下一行的列名称)。因此,通过这样做,

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

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

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

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)

Comment from @backlin

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文