我正在尝试使用tidyquant或dplyr创建一个简单的dplyr语句。
我现在拥有的是;
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包可以在xts数据上使用dplyr函数,所以我也试图使用tidyquant来解决这个问题。
以下操作有效,但将数据从xts格式中删除。
x <- GOOG %>%
data.frame() %>%
mutate(Direction = ifelse(Close < Open, 1, 0))发布于 2018-12-08 14:03:41
这里的问题不在于ifelse。它是关于mutate和事实
class(GOOG)
# [1] "xts" "zoo"在这种情况下,您实际上不会从mutate获得任何东西,所以您可以只使用
GOOG$Direction <- with(GOOG, ifelse(Close < Open, 1, 0))但是,您也可以在tidyquant中使用quantmod而不是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,但用transform代替mutate
GOOG %>% transform(Direction = ifelse(Close < Open, 1, 0))https://stackoverflow.com/questions/53683228
复制相似问题