【问题标题】:How a simpler derive is written in R by group (in R, ggplot, dplyr, tidyverse)?如何按组在 R 中编写更简单的派生(在 R、ggplot、dplyr、tidyverse 中)?
【发布时间】:2019-09-20 10:04:37
【问题描述】:

我在一列中有两个数据,它们的名称在 y 轴上,日期时间在 x 轴上。

我尝试计算每两个数据的数字导数,但我不明白 R 中的导数。(我一直在寻找 stats::Ddiff,但它不起作用)。

f(x)=(t_n-t_n-1)/(date_time_n / date_time_n -1)

其中 f(x) 将是我的计算列。

即用执行此操作的函数在下面的代码中替换我的calc=t/10。 (我更喜欢 tidyverse / dplyr)

链接

下面: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


    【解决方案1】:

    据我了解,您希望使用当前和以前的 tdate_heure 值计算 calc。要获取特定列中前一行的值,可以使用lag,如下:

    datas<- (datas
             %>% mutate (
               calc = (t - lag(t)) / as.integer((date_heure - lag(date_heure)))
            )
    )
    

    请注意,第一行的calc 的值将是NA。因此,在绘制图形之前,您可能需要跳过并为其指定一个默认值。

    例如:

    datas <- datas[-1,]  # To skip the first `NA` value
    datas[1,]$calc <- 0  # To give it a default value of `0`
    

    希望对您有所帮助。

    【讨论】:

    • 谢谢。它有效,数据和情节似乎是我的用户在谈论它。一旦我的用户在某些日子(~星期二)看到它,我就会接受。
    • 很高兴听到它对您有用。你现在可以给我的答案一个赞成票,然后再接受它:-)
    • 谢谢。似乎没问题...我验证。 (我已经删除了关于 ggplot 的 cmets 并且对于这个问题不准确)。
    【解决方案2】:

    以下行将添加一个新行,其中包含每组的滞后时间值。

    library(dplyr)
    data <- 
        data %>%
        group_by(groups) %>%
        mutate(lag.value = dplyr::lag(value, n = 1, default = NA))
    

    同样,您可以添加另一列,通过您选择的公式计算第一个(前向)差异系数。请注意,如果您有 NA 值,事情可能会变得更加复杂。

    您可以在How to create a lag variable within each group?找到更多解释和替代方法

    【讨论】:

    • 谢谢你,但如果你愿意,你能用我的变量修改你的代码吗?我接受你的回答。我试过datas &lt;-( datas %&gt;% group_by(orig) %&gt;% mutate(calc = dplyr::lag(t, n = 1, default = NA))),它显示数据但ggplot不起作用。
    • 要接受您的回答,我还必须在几天后等待我的用户的回答。
    • 感谢您的链接。
    猜你喜欢
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-06
    • 2021-05-15
    • 2021-02-20
    相关资源
    最近更新 更多