首页 > 解决方案 > 如何使用R中的dplyr在列中减去奇数行数的偶数行数

问题描述

我的数据框看起来像这样

df <-data.frame(col1=c(1,2,3,4), col2=c(5,6,7,8), time=rep(c("0h","72h"),2))
  col1 col2 time
1    1    5   0h
2    2    6  72h
3    3    7   0h
4    4    8  72h

我想使用 mutate_across 或任何其他 dplyr 函数(最好)从每列的前一行中减去 72h 的值和 0h 的值。

我希望我的数据看起来像这样

  col1 col2 time
     1    1   72h
     1    1   72h

标签: rdplyrtidyverse

解决方案


根据

df <-data.frame(col1=c(1,2,3,4), col2=c(5,6,7,8), time=rep(c(0,72),2))

df[c(FALSE,TRUE), ] - df[c(TRUE, FALSE), ]
#>   col1 col2 time
#> 2    1    1   72
#> 4    1    1   72

reprex 包于 2021-07-06 创建 (v2.0.0 )

tidyverse 使用@Emir Dakin 的方法

library(tidyverse)
df <-data.frame(col1=c(1,2,3,4), col2=c(5,6,7,8), time=rep(c("0h", "72h"),2))

df %>%
  mutate(across(where(is.numeric), ~.x - lag(.x, default = first(.x)))) %>%
  filter(time == "72h")
#>   col1 col2 time
#> 1    1    1  72h
#> 2    1    1  72h

reprex 包于 2021-07-06 创建 (v2.0.0 )


推荐阅读