[英]Loop based on multiple conditions in r
我有一個這樣的數據集,
x time
1 TRUE 10
2 FALSE 20
3 TRUE 11
4 FALSE 10
5 TRUE 16
6 FALSE 2
7 TRUE 17
8 FALSE 6
9 TRUE 11
10 FALSE 7
11 TRUE 20
12 FALSE 3
13 TRUE 10
14 FALSE 4
15 TRUE 2
16 FALSE 10
17 TRUE 3
18 FALSE 6
使用 r,我想生成一個新變量來標記基於 x 和時間的某些條件。 具體來說,我想從頭開始搜索數據,當“ x為 TRUE 且時間長於 15”時,我想找到下一行“ x為 FALSE 且時間長於 5”,並標記它在一個新變量中。 在整個數據集中重復執行此操作。
我想得到的output是這樣的
x time Marker
1 TRUE 10
2 FALSE 20
3 TRUE 11
4 FALSE 10
5 TRUE 16
6 FALSE 2
7 TRUE 17
8 FALSE 6 Meet
9 TRUE 11
10 FALSE 7
11 TRUE 20
12 FALSE 3
13 TRUE 10
14 FALSE 4
15 TRUE 2
16 FALSE 10 Meet
17 TRUE 3
18 FALSE 6
我正在考慮在 r 中循環執行此操作,因為我有一個很長的數據集,但無法弄清楚。 任何意見,將不勝感激。
假設你的 data.frame 被稱為d
look <- FALSE
d$Marker <- NA
for(i in 1:nrow(d)){
if(d$x[i] & d$time[i] > 15){
look <- TRUE
next
}
if(look){
if(!d$x[i] & d$time[i] > 5){
d$Marker[i] <- "Meet"
look <- FALSE
}
}
}
library(dplyr)
mark_first <- function(x) {
out <- rep('', length(x))
if (!any(x)) return(out)
out[which.max(x)] <- "Meet"
return(out)
}
d %>%
group_by(g = cumsum(x & (time > 15))) %>%
mutate(Marker = mark_first(!x & time < 5))
# A tibble: 18 × 4 # Groups: g [4] x time g Marker <lgl> <int> <int> <chr> 1 TRUE 10 0 "" 2 FALSE 20 0 "" 3 TRUE 11 0 "" 4 FALSE 10 0 "" 5 TRUE 16 1 "" 6 FALSE 2 1 "Meet" 7 TRUE 17 2 "" 8 FALSE 6 2 "" 9 TRUE 11 2 "" 10 FALSE 7 2 "" 11 TRUE 20 3 "" 12 FALSE 3 3 "Meet" 13 TRUE 10 3 "" 14 FALSE 4 3 "" 15 TRUE 2 3 "" 16 FALSE 10 3 "" 17 TRUE 3 3 "" 18 FALSE 6 3 ""
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.