r - 如何使用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
解决方案
根据
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 )
推荐阅读
- node.js - 我正在尝试通过 NPM 将 Mongoose 下载到我的 Node.js 项目中
- html - 如何在 SwiftUI 中创建一个列表视图,每个列表项都是一个 WKWebView(我的实现非常慢并且有问题)
- docker - Docker 复制命令失败?
- python-3.x - 当我的脸移动得太快时,OpenCV 人脸检测会中断
- tomcat - Run Netty and tomcat on same port but different ip in a single server (Netty opens at localhost)
- python-3.x - 加速 Python 程序(自适应中值滤波器)
- typescript - 基于数组内容的条件类型/接口
- javascript - 如何在类组件中使用导航?反应原生
- ios - 在swiftui中按钮的触摸动作播放音频
- windows - 无法打开新的 Jupyter 笔记本 [权限被拒绝]