【发布时间】:2016-11-19 19:45:04
【问题描述】:
我有兴趣在 zoo 对象中计算一些新变量。我喜欢dplyr-mutate-方式,但我不知道如何在zoo 对象内变异。如果我使用transform,我似乎仅限于计算对象内部已经存在的变量。我显然可以在单独的步骤中完成它,但我想在 zoo 对象中我可能忽略了一些方便的工作方式?我查看了this answer,这激发了我的问题,以及this question,但它们都没有解决我的具体问题。
这里有一些代码展示了我想要做什么,
df <- data.frame(dta=paste0("2016-11-", 19:24), a = 3:8, b = 9:14)
# install.packages(c("dplyr"), dependencies = TRUE)
library(dplyr)
df %>%
mutate(c = log(a) * log(b),
dc = c - lag(c, 1)
)
# dta a b c dc
# 1 2016-11-19 3 9 2.413898 NA
# 2 2016-11-20 4 10 3.192061 0.7781628
# 3 2016-11-21 5 11 3.859264 0.6672028
# 4 2016-11-22 6 12 4.452355 0.5930915
# 5 2016-11-23 7 13 4.991161 0.5388060
# 6 2016-11-24 8 14 5.487765 0.4966045
# install.packages(c("zoo"), dependencies = TRUE)
library(zoo)
df.z <- read.zoo(df)
# install.packages(c("magrittr"), dependencies = TRUE)
library(magrittr)
df.z %>% transform(c = log(a) * log(b), dc = c - lag(c, 1))
# Error in x[seq_len(xlen - n)] :
# object of type 'builtin' is not subsettable
# the clumsy workaround
df.z.1 <- df.z %>% transform(c = log(a) * log(b))
df.z.2 <- df.z.1 %>% transform(dc = c - lag(c, 1))
df.z.2
# a b c dc
# 2016-11-19 3 9 2.413898 NA
# 2016-11-20 4 10 3.192061 0.7781628
# 2016-11-21 5 11 3.859264 0.6672028
# 2016-11-22 6 12 4.452355 0.5930915
# 2016-11-23 7 13 4.991161 0.5388060
# 2016-11-24 8 14 5.487765 0.4966045
【问题讨论】:
-
嗨,
zoo在内部使用matrix来存储数据,所以您可以在matrix中将您的问题定义为mutate以获得更广泛的受众。