【问题标题】:Change row names in R Studio在 R Studio 中更改行名称
【发布时间】:2020-05-24 20:36:56
【问题描述】:

我尝试将行名从日期更改为字符;

library(quantmod)

mdate <- "2019-05-01"
edate <- "2019-05-08"
tickers <- c("MMM","C", "AAPL", "IBM", "AMZN")
rnames <- c("Open_1", "Open_2", "Open_3", "Open_4", "Open_D")
portfolioPrices <- NULL
for(ticker in tickers)
  portfolioPrices <- cbind(portfolioPrices, getSymbols(ticker, from = mdate, to = edate, auto.assign = F)[,1])
  colnames(portfolioPrices) = tickers
  rownames(portfolioPrices) = rnames

这些代码给了我:

如您所见,行名没有改变。我想把它们从日期改成rnames &lt;- c("Open_1", "Open_2", "Open_3", "Open_4", "Open_D")

我能做些什么来实现这个目标?

【问题讨论】:

  • portfolioPrices 是一个xts 对象(检查str(portfolioPrices),因此不能有行名。根据文档(?dimnames.xts)“xts 对象的设计旨在用于轻量级管理时间索引数据。在这种设计中,行名是多余的,而且在内存消耗和内部复制成本方面也相当繁重。"
  • 感谢您提供的信息。那么,您能告诉我将 rnames 添加到日期旁边的新列中吗?我用了cbind,但是没用。

标签: r quantmod rbind


【解决方案1】:

您可以使用“timetk”包中的“tk_tbl”函数将xts对象转换为数据框。

library(quantmod)
library(timetk)

mdate <- "2019-05-01"
edate <- "2019-05-08"
tickers <- c("MMM","C", "AAPL", "IBM", "AMZN")
rnames <- c("Open_1", "Open_2", "Open_3", "Open_4", "Open_D")

portfolioPrices <- NULL
for(ticker in tickers)
  portfolioPrices <- cbind(portfolioPrices, getSymbols(ticker, from = mdate, to = edate, auto.assign = F)[,1])

#tk_tbl convert "xts" object to data frame, but the original dates will be transformed into a new column named "index" 
timetk::tk_tbl(portfolioPrices)
   # A tibble: 5 x 6
      index      MMM.Open C.Open AAPL.Open IBM.Open AMZN.Open
      <date>        <dbl>  <dbl>     <dbl>    <dbl>     <dbl>
    1 2019-05-01     189.   70.7      210.     141.     1933.
    2 2019-05-02     184.   69.7      210.     140.     1913.
    3 2019-05-03     186.   70.4      211.     140.     1949 
    4 2019-05-06     182.   69.1      204.     138.     1918.
    5 2019-05-07     182.   69.3      206.     139.     1940.

#remove the "index" column and reassign colnames and rownames
portfolioPrices <- timetk::tk_tbl(portfolioPrices)[, -1] 
colnames(portfolioPrices) = tickers
rownames(portfolioPrices) = rnames

【讨论】:

  • 非常感谢!!
  • @DongchulPark 如果答案对您有用,请随时accept the answer,如果您觉得它对您有用,请点击左侧投票按钮旁边的复选标记。 :-) 每个帖子只能接受一个答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-19
  • 2015-01-12
  • 1970-01-01
相关资源
最近更新 更多