下面我有一个长格式的数据帧子集。我需要做的是根据Response和Date列调整value列。我需要调整Response =光合作用的行的值列。如果Response =光合作用,我需要减去Response =呼吸的值。我还在不同的日期重复测量,所以呼吸和光合作用的值需要来自相同的日期。我认为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"))发布于 2019-12-02 06:43:07
我们可以只做一次diff,因为数据已经分组,每组只有2个观察值
library(dplyr)
test %>%
mutate(value = c(first(value), diff(value)))https://stackoverflow.com/questions/59130594
复制相似问题