1

我正在尝试使用or创建一个简单的ifelse语句。tidyquantdplyr

我目前拥有的是;

from <- "2017-07-09"
to <- "2018-12-01"
getSymbols("GOOG", from = from, to = to, src = "yahoo", adjust = TRUE)

colnames(GOOG) <- c("Open", "High", "Low", "Close", "Volume", "Adjusted")

library(dplyr)
library(tidyquant)

GOOG %>%
  mutate(Direction = ifelse(Close < Open, 1, 0))

返回错误:

Error in UseMethod("mutate_") : 
  no applicable method for 'mutate_' applied to an object of class "c('xts', 'zoo')"

我知道这个tidyquant包可以dplyr对数据使用函数,xts所以我也试图用它tidyquant来解决这个问题。

以下工作但将数据从xts格式中取出。

x <- GOOG %>%
  data.frame() %>%
  mutate(Direction = ifelse(Close < Open, 1, 0))
4

1 回答 1

2

这里的问题不是关于ifelse. 这是关于mutate和事实

class(GOOG)
# [1] "xts" "zoo"

在这种情况下,无论如何您都不会真正获得任何收益mutate,因此您可以使用

GOOG$Direction <- with(GOOG, ifelse(Close < Open, 1, 0))

但是,您也可以使用tidyquant而不是quantmodwith getSymbols

GOOG <- tq_get("GOOG", from = from, to = to)
GOOG %>% mutate(Direction = ifelse(close < open, 1, 0))
# A tibble: 354 x 8
#   date        open  high   low close  volume adjusted Direction
#   <date>     <dbl> <dbl> <dbl> <dbl>   <dbl>    <dbl>     <dbl>
# 1 2017-07-10  922.  930.  920.  929. 1192800     929.         0
# 2 2017-07-11  930.  931.  922   930. 1113200     930.         0
# 3 2017-07-12  939.  946.  934.  944. 1532100     944.         0
# ... with 351 more rows

然后这会起作用,因为

class(GOOG)
# [1] "tbl_df"     "tbl"        "data.frame"

另一种选择是继续使用quantmod但替换mutatetransform

GOOG %>% transform(Direction = ifelse(Close < Open, 1, 0))
于 2018-12-08T14:03:41.867 回答