1

I am trying to create a simple ifelse statement using tidyquant or dplyr.

What I currently have is;

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

Which returns an error:

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

I know the tidyquant package can use dplyr functions on xts data so I am also trying to use the tidyquant to get around this issue.

The following works but takes the data out of the xts format.

x <- GOOG %>%
  data.frame() %>%
  mutate(Direction = ifelse(Close < Open, 1, 0))
user113156
  • 6,761
  • 5
  • 35
  • 81

1 Answers1

2

The issue here is not about ifelse. It is about mutate and the fact that

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

In this case you wouldn't really gain anything from mutate anyway, so you could just use

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

However, you could also use tidyquant instead of quantmod with 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

This then works because

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

Yet another option would be to keep using quantmod but to replace mutate by transform:

GOOG %>% transform(Direction = ifelse(Close < Open, 1, 0))
Julius Vainora
  • 47,421
  • 9
  • 90
  • 102