小编Sam*_*amo的帖子

从时间跨度(例如"15分钟"或"2秒")到"00:15:00"或"00:00:02"

我正在寻找R函数的所有帮助,它将把时间跨度,例如"15分钟"或"1小时"或"6秒"或"1天"转换为日期时间对象,如"00:15:00"或"01: 00:00"或"00:00:06"或"1960-01-02 00:00:00"(对此不确定).我确信这样的函数存在,或者有一种简洁的方法可以避免编程...

更具体地说,我想做这样的事情(使用组合函数名称transform.span.to.time):

library(chron)

times(transform.span.to.time("15 min"))
Run Code Online (Sandbox Code Playgroud)

这应该产生相同的结果

times("00:15:00")
Run Code Online (Sandbox Code Playgroud)

像transform.span.to.time("15分钟")之类的函数是否存在返回类似"00:15:00"的函数,或者是否存在如何做到这一点的技巧?

r

5
推荐指数
2
解决办法
342
查看次数

使用quantmod :: chart_Series()中的xlim/ylim或xrange/yrange覆盖y-scale和x-scale - 不可能?

我试图在quantmod :: chart_Series()之上绘制一些支持/阻力线.问题是有趣的支持/阻力线在当前时间之外(低于或高于)系列数据范围(我还希望将图表向右扩展到超出数据的最后时间戳).

查看quantmod :: chart_Series()的源代码,我看不到指定ylim/xlim的方法,或者使用yrange来覆盖y-scale,使用quantmod :: chartSeries在"旧时代"中可能实现的.这里的评论https://r-forge.r-project.org/scm/viewvc.php?view=rev&root=quantmod&revision=520也在确认我的预感......

我的诊断是否正确,或者是否有一种方法可以在quantmod :: chart_Series中实现y-scale覆盖?任何想法如何做我想要的高度赞赏.

谢谢.

最好,萨摩

finance r quantmod

5
推荐指数
1
解决办法
1056
查看次数

quantmod :: chart_Series()bug?

我想使用quantmod :: chart_Series()绘制SPX图表,并在下面绘制GDP的变化和GDP变化的12个月SMA.无论我如何尝试(我使用什么组合)发生错误或quantmod :: chart_Series()只显示部分图.

require(quantmod)

FRED.symbols <- c("GDPC96")

getSymbols(FRED.symbols, src="FRED")
SPX <- getSymbols("^GSPC", auto.assign=FALSE, from="1900-01-01")

subset="2000/"

chart_Series(SPX, subset=subset)
add_TA(GDPC96)
add_TA(ROC(GDPC96, type="discrete"))
add_TA(SMA(ROC(GDPC96, type="discrete"), n=4), on=3, col="blue")
Run Code Online (Sandbox Code Playgroud)

编辑:实际上,在我看来,这是使用季度数据时的quantmod :: chart_series()问题:

subset <- "2000/"
chart_Series(to.quarterly(SPX, drop.time=TRUE), subset=subset)
add_TA(SMA(Cl(to.quarterly(SPX, drop.time=TRUE))))

> subset <- "2000/"
> chart_Series(to.quarterly(SPX, drop.time=TRUE), subset=subset)
> add_TA(SMA(Cl(to.quarterly(SPX, drop.time=TRUE))))
Error in xy.coords(x, y) : 'x' and 'y' lengths differ
In addition: Warning messages:
1: In as_numeric(H) : NAs introduced by coercion
2: In as_numeric(H) : NAs introduced by coercion
3: …
Run Code Online (Sandbox Code Playgroud)

finance r xts quantmod

5
推荐指数
1
解决办法
1262
查看次数

如何防止错误后执行更多代码步骤?

我怎样才能确保在"捕获"错误并记录之后不再执行其他代码步骤(我不想使用q())?

我的使用场景是这样的: - 做一些计算 - 如果发生错误记录它 - 停止执行代码中的任何进一步的步骤

我尝试使用下面的代码示例解决此问题(使用print代替true logging函数):

handleMySimpleError<-function(e, text) {
    # Let's log the error
    print(paste0(text, ": ", e))
    # This should stop execution of any further steps but it doesn't
    stop("Now, stop. For real.")
}

print("Starting execution...")
tryCatch(
    stop("My simple error."),
    error=function(e) {handleMySimpleError(e, "could not finish due to")}, finnaly=NULL
)
print("Successfully ended execution...")
Run Code Online (Sandbox Code Playgroud)

我不知何故希望打印("成功结束执行......")永远不会被执行......但是,这是我得到的输出:

> handleMySimpleError<-function(e, text) {
+   # Let's log the error
+   print(paste0(text, ": ", e))
+   # This should stop execution of …
Run Code Online (Sandbox Code Playgroud)

r

5
推荐指数
1
解决办法
1487
查看次数

删除所有点,但字符串中的第一个点

我想替换除了第一个连续点以外的所有点.这是我想要的一个例子:

> names.orig <- c("test & best", "test & worse &&&&  ? do")
> names <- make.names(names.orig)
> names
[1] "test...best"             "test...worse.........do"
> 
> # But I want this instead:
> # [1] "test.best"             "test.worse.do"
> 
> # Desperatley tried:
> gsub("\\.{2, }", "", names)
[1] "testbest"    "testworsedo"
> gsub("\\G((?!^).*?|[^\\.]*\\.*?)\\.", "", names)
Error in gsub("\\G((?!^).*?|[^\\.]*\\.*?)\\.", "", names) : 
  invalid regular expression '\G((?!^).*?|[^\.]*\.*?)\.', reason 'Invalid regexp'
> # etc.
> 
> # The only thing that works for me is this …
Run Code Online (Sandbox Code Playgroud)

regex r

5
推荐指数
1
解决办法
458
查看次数

如何使用foreach克服内存限制

我正在尝试处理> 10000 xts保存在磁盘上的对象,每个加载到R时大约为0.2 GB.我想使用foreach并行处理这些对象.我的代码适用于100 xts对象,我在内存中预先加载,导出等.但是在> 100 xts对象后,我在我的机器上达到了内存限制.

我想要做的例子:

require(TTR)
require(doMPI)
require(foreach)

test.data <- runif(n=250*10*60*24)

xts.1 <- xts(test.data, order.by=as.Date(1:length(test.data)))
xts.1 <- cbind(xts.1, xts.1, xts.1, xts.1, xts.1, xts.1)

colnames(xts.1) <- c("Open", "High", "Low", "Close", "Volume", "Adjusted")

print(object.size(xts.1), units="Gb")

xts.2 <- xts.1
xts.3 <- xts.1
xts.4 <- xts.1

save(xts.1, file="xts.1.rda")
save(xts.2, file="xts.2.rda")
save(xts.3, file="xts.3.rda")
save(xts.4, file="xts.4.rda")

names <- c("xts.1", "xts.2", "xts.3", "xts.4")

rm(xts.1)
rm(xts.2)
rm(xts.3)
rm(xts.4)

cl <- startMPIcluster(count=2) # Use 2 cores
registerDoMPI(cl)

result <- foreach(name=names, 
                  .combine=cbind, 
                  .multicombine=TRUE, 
                  .inorder=FALSE, 
                  .packages=c("TTR")) %dopar% { …
Run Code Online (Sandbox Code Playgroud)

memory parallel-processing foreach memory-management r

5
推荐指数
1
解决办法
960
查看次数

Rmarkdown重叠输出

我报告了一个问题https://github.com/rstudio/rmarkdown/issues/967,我想知道是否有解决方法(如何使这项工作)?

在此输入图像描述

下面的可重复示例(改变n和nGroup以查看效果 - 当n = 100且nGroup = 10时不重叠):

---
title: "Test links to sections in DT"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo=FALSE)
knitr::opts_chunk$set(message=FALSE)
knitr::opts_chunk$set(warning=FALSE)

## DT Test

```{r echo=FALSE}
library(DT)

n <- 1000
nGroup <- 100

testDF <- data.frame(text=paste0("Section", 1:n),
                     number=1:n,
                     group=rep(1:(n/nGroup), n/nGroup))

datatable(head(testDF), caption="Whole table", rownames=FALSE, escape=FALSE, options=list(paging=FALSE, info=FALSE))

getDT<-function(x) {
  a <- list()
  a[[1]] <- htmltools::tags$h3("test1")
  a[[2]] <- datatable(x[, c("text", "number")], caption=htmltools::tags$caption(style="caption-side: top; text-align: left;", "Group: ", htmltools::strong(x$group)), rownames=FALSE, escape=FALSE, filter=c("none"), options=list(paging=FALSE, info=FALSE))
  a[[3]] <- …
Run Code Online (Sandbox Code Playgroud)

r r-markdown dt htmlwidgets

5
推荐指数
1
解决办法
781
查看次数

强制 RStudio 使用 Python 3.6 而不是 Python 2.7

我想在 RStudio 中执行 Python 脚本(这不是通过 R 脚本中的 reticulate 调用 Python,而是在 RStudio 中运行 Python 脚本,尽管正如我所见,使用了 reticulate)。我有一个非常简单的脚本,名为 test.py,其中包含以下命令:

print("test")
Run Code Online (Sandbox Code Playgroud)

当我运行此命令时,RStudio 使用 Python 2.7 而不是系统默认的 3.6:

> reticulate::repl_python()
Python 2.7.15 (/usr/bin/python)
Reticulate 1.10 REPL -- A Python interpreter in R.
>>> print("test")
test
>>> 
>>> 
Run Code Online (Sandbox Code Playgroud)

如何强制 RStudio 使用默认系统 Python 版本(在我的例子中为 3.6)而不是 2.7?

Python 的默认版本:

username@usernameVB:~$ python
Python 3.6.7 (default, Oct 22 2018, 11:32:17) 
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 
Run Code Online (Sandbox Code Playgroud)

编辑:我找到了这个解决方法:转到控制台并在运行 Python 脚本之前执行以下命令:

> library(reticulate)
> …
Run Code Online (Sandbox Code Playgroud)

python rstudio

5
推荐指数
1
解决办法
914
查看次数

加快WMA(加权移动平均线)计算

我试图在15天的条形图上计算指数移动平均线,但是想要在每天(结束日)/条形图上看到15天条形EMA的"演变".所以,这意味着我有15天的酒吧.当新数据每天进入时,我想使用新信息重新计算EMA.实际上我有15天的酒吧然后,每天后我的新15天酒吧开始增长,每个新的酒吧应该用于EMA计算以及之前的15天酒吧.

让我们说我们从2012-01-01开始(我们有这个例子的每个日历日的数据),在2012-01-15结束时我们有第一个完整的15天吧.在2012-03-01完成4个完整的15天栏后,我们可以开始计算4 bar EMA(EMA(x,n = 4)).在2012-03-02结束时,我们使用到目前为止的信息并在2012-03-02计算EMA,假装2012-03-02的OHLC是15天的正在进行中.因此,我们在2012-03-02获取4个完整的条形和条形并计算EMA(x,n = 4).然后我们再等一天,看看正在进行的新15天酒吧发生了什么(请参阅下面的函数to.period.cumulative了解详细信息)并计算EMA的新值......所以在接下来的15天内......见函数EMA.cumulative以下详细信息......

请在下面找到我能想到的东西.性能对我来说是不可接受的,因为我的R知识有限,我无法更快地完成.

library(quantmod)

do.call.rbind <- function(lst) {
    while(length(lst) > 1) {
        idxlst <- seq(from=1, to=length(lst), by=2)

        lst <- lapply(idxlst, function(i) {
                    if(i==length(lst)) { return(lst[[i]]) }

                    return(rbind(lst[[i]], lst[[i+1]]))
                })
    }
    lst[[1]]
}

to.period.cumulative <- function(x, name=NULL, period="days", numPeriods=15) {
    if(is.null(name))
        name <- deparse(substitute(x))

    cnames <- c("Open", "High", "Low", "Close")
    if (has.Vo(x)) 
        cnames <- c(cnames, "Volume")

    cnames <- paste(name, cnames, sep=".") 

    if (quantmod:::is.OHLCV(x)) {
        x <- OHLCV(x)
        out <- do.call.rbind( 
                lapply(split(x, f=period, k=numPeriods), 
                        function(x) cbind(rep(first(x[,1]), …
Run Code Online (Sandbox Code Playgroud)

finance r

4
推荐指数
1
解决办法
1791
查看次数

犰狳:将立方体子视图(管)转换为矢量

当我尝试从armadillo cube(使用tube或slice)获取vector/double时出现编译错误.如何从立方体到(行)vec?我找不到优雅的演员/变形犰狳功能.

#include <RcppArmadillo.h>
//#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
void testarma() {
  arma::mat B;

  B << 0.555950 << 0.274690 << 0.540605 << 0.798938 << arma::endr
    << 0.108929 << 0.830123 << 0.891726 << 0.895283 << arma::endr
    << 0.948014 << 0.973234 << 0.216504 << 0.883152 << arma::endr
    << 0.023787 << 0.675382 << 0.231751 << 0.450332 << arma::endr;

  B.print("B:");

  // cubes ("3D matrices")
  arma::cube Q(B.n_rows, B.n_cols, 4);

  Q.slice(0) = B;
  Q.slice(1) = 2.0 * B;
  Q.slice(2) = 3.0 * B;
  Q.slice(3) …
Run Code Online (Sandbox Code Playgroud)

c++ armadillo rcpp

1
推荐指数
1
解决办法
1192
查看次数