![](/img/trans.png)
[英]how to arrange odd numbers in descending and even even numbers in ascending order in dplyr
[英]How to subtract even row numbers with odd row numbers across columns using dplyr in R
我的數據框看起來像這樣
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 包( v2.0.0 ) 於 2021 年 7 月 6 日創建
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
如果數據按照您顯示的方式排列整齊,您可以使用lag
函數。 這是一個非常簡單的應用程序,但它應該可以工作,我認為除了mutate
之外你不需要其他任何東西:
df %>%
mutate(col1 = col1 - lag(col1, default = first(col1)),
col2 = col2 - lag(col2, default = first(col2))) %>%
filter(time == "72h")
通過埃米爾達金的回答,我添加了一個帶有時間發生順序的控件:
library(dplyr)
df %>% group_by(time) %>% mutate(sl= seq(time)) %>% group_by(sl) %>%
mutate(col1 = col1 - lag(col1, default = first(col1), order_by = time),
col2 = col2 - lag(col2, default = first(col2), order_by = time)) %>%
ungroup() %>% filter(time == "72h") %>% select(col1, col2, time)
# A tibble: 2 x 3
col1 col2 time
<dbl> <dbl> <chr>
1 1 1 72h
2 1 1 72h
或者:
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(id = rep(seq(nrow(df) / 2), each = 2), # create an id of what belongs together
tmp = rep(c("start", "end"), nrow(df) / 2),
time = as.numeric(str_remove(time, "h"))) %>%
mutate_at(vars("col1":"time"), ~if_else(tmp == "start", .x * -1, .x)) %>%
group_by(id) %>%
summarise_at(vars("col1":"time"), sum)
# # A tibble: 2 x 4
# id col1 col2 time
# <int> <dbl> <dbl> <dbl>
# 1 1 1 1 72
# 2 2 1 1 72
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.