【发布时间】:2019-09-20 10:04:37
【问题描述】:
我在一列中有两个数据,它们的名称在 y 轴上,日期时间在 x 轴上。
我尝试计算每两个数据的数字导数,但我不明白 R 中的导数。(我一直在寻找 stats::D 或 diff,但它不起作用)。
f(x)=(t_n-t_n-1)/(date_time_n / date_time_n -1)
其中 f(x) 将是我的计算列。
即用执行此操作的函数在下面的代码中替换我的calc=t/10。 (我更喜欢 tidyverse / dplyr)
链接
- Calculate the derivative of a data-function in r
- 我之前的问题To add a legend by shape in ggplot ( added 2nd question after: to calculate numeric deriv)
下面:calc=t/10 的 ggplot 图片,其中calc 将被派生替换。
library(tidyverse)
library(ggplot2)
datas<-data.frame(
t = c(
50 + c(0, cumsum(runif(9, -7, 7))),
70 + c(0, cumsum(runif(9, -10, 10)))
),
orig=c(rep("s1",10),rep("s2",10)),
date_heure = rep(
seq(from=as.POSIXct("2012-1-1 0:00", tz="UTC"),by="hour", length=10) ,
2
)
)
datas<- (datas
%>% mutate (
calc=t/10
)
)
(
ggplot(datas)
+ geom_line(mapping=aes(x = date_heure, y = t, color=orig, linetype = "s1"))
+ geom_line(mapping=aes(x = date_heure, y = calc, color=orig, linetype = "s2"))
+ scale_y_continuous(name = "t", sec.axis = sec_axis(trans=~(range(datas$calc)), name = "calc"))
+ geom_point(mapping = aes(x = date_heure, y = calc, color=orig), shape = 21, fill = "white")
+ scale_color_manual(name = "calc", values=c("red", "blue"))
+ scale_linetype_manual(name = "orig", values = c('solid', 'solid'),
guide = guide_legend(override.aes = list(colour=c("red", "blue"))))
)
【问题讨论】:
标签: r ggplot2 dplyr statistics