【问题标题】:Conditional subtraction of row values based on 2 conditions基于 2 个条件的行值的条件减法
【发布时间】:2019-12-01 22:32:59
【问题描述】:

我在下面有一个长格式的数据框。我需要做的是根据响应和日期列调整值列。我需要调整响应 = 光合作用的行的值列。如果响应 = 光合作用,我需要减去响应 = 呼吸的值。我还在不同日期重复测量,因此呼吸和光合作用值需要来自同一日期。我认为 ifelse 会起作用,但我无法正确使用语法。

test <- structure(list(variable = c(221L, 221L, 44L, 44L, 221L, 221L, 44L, 44L), value = 
c(-1.21625718690742, 1.15247376323723, -0.374982444111372, -0.1080667523228, 
-0.344666861319387, 0.453100231803574, -0.200976470494833, 0.100700409657002), Date = 
structure(c(18155, 18155, 18155, 18155, 18171, 18171, 18171, 18171), class = "Date"), 
Response = c("Respiration", "Photosynthesis", "Respiration", "Photosynthesis", "Respiration", 
"Photosynthesis", "Respiration", "Photosynthesis")), row.names = c(NA, -8L), groups = 
structure(list(variable = c(44L, 44L, 221L, 221L), Date = structure(c(18155, 18171, 18155, 
18171), class = "Date"), .rows = list(3:4, 7:8, 1:2, 5:6)), row.names = c(NA, -4L), class = 
c("tbl_df", "tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", "tbl_df", "tbl", 
"data.frame"))

【问题讨论】:

    标签: r if-statement


    【解决方案1】:

    我们可以只做一个diff,因为数据已经分组并且每组只有 2 个观察结果

    library(dplyr)
    test %>%
        mutate(value = c(first(value), diff(value)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-27
      • 2017-07-19
      • 1970-01-01
      • 1970-01-01
      • 2011-01-22
      相关资源
      最近更新 更多