我需要知道如何洗掉 data.frame (DF1) 中某個點之前的所有行
我想洗掉編號最小的行之前的所有行(按 ID 分組并按日期排列)
DF1
ID Date Value
1 2/11/2021 0
1 2/12/2021 2
1 2/13/2021 1
1 2/14/2021 0
1 2/15/2021 1
1 2/16/2021 -37
1 2/17/2021 0
1 2/18/2021 1
1 2/19/2021 -2
我試圖訪問的資料框(DF2):
DF2
ID Date Value
1 2/16/2021 -37
1 2/17/2021 0
1 2/18/2021 1
1 2/19/2021 -2
謝謝!
uj5u.com熱心網友回復:
您可以使用 -
library(dplyr)
df %>%
mutate(Date = as.Date(Date, '%m/%d/%Y')) %>%
arrange(ID, Date) %>%
group_by(ID) %>%
slice(which.min(Value):n()) %>%
ungroup
# ID Date Value
# <int> <date> <int>
#1 1 2021-02-16 -37
#2 1 2021-02-17 0
#3 1 2021-02-18 1
#4 1 2021-02-19 -2
uj5u.com熱心網友回復:
我們可能會做
library(dplyr)
library(lubridate)
DF1 %>%
arrange(ID, mdy(Date)) %>%
group_by(ID) %>%
slice(match(min(Value), Value):n()) %>%
ungroup
# A tibble: 4 × 3
ID Date Value
<int> <chr> <int>
1 1 2/16/2021 -37
2 1 2/17/2021 0
3 1 2/18/2021 1
4 1 2/19/2021 -2
資料
DF1 <- structure(list(ID = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), Date = c("2/11/2021",
"2/12/2021", "2/13/2021", "2/14/2021", "2/15/2021", "2/16/2021",
"2/17/2021", "2/18/2021", "2/19/2021"), Value = c(0L, 2L, 1L,
0L, 1L, -37L, 0L, 1L, -2L)), class = "data.frame", row.names = c(NA,
-9L))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/333101.html
上一篇:如何洗掉括號但將文本保留在R中
下一篇:在R中回圈資料幀洗掉程序
