dplyr/tidyquant xts 中的简单 ifelse 语句
Simple ifelse statement in dplyr/tidyquant xts
我正在尝试使用 tidyquant
或 dplyr
创建一个简单的 ifelse
语句。
我目前拥有的是;
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))
其中returns一个错误:
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))
这里的问题与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
但将 mutate
替换为 transform
:
GOOG %>% transform(Direction = ifelse(Close < Open, 1, 0))
我正在尝试使用 tidyquant
或 dplyr
创建一个简单的 ifelse
语句。
我目前拥有的是;
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))
其中returns一个错误:
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))
这里的问题与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
但将 mutate
替换为 transform
:
GOOG %>% transform(Direction = ifelse(Close < Open, 1, 0))