我在r
中有以下数据框 ship_no equip_name yard
ABC 501 4A
ABC 501 4A
ABC 501 4D
ABC 501 4D
ABC 501 4B
ABC 501 5B
ABC 501 5C
ABC 501 5E
DEF 502 4D
DEF 502 4D
DEF 502 4C
DEF 502 5C
DEF 502 4L
DEF 502 4L
DEF 502 4L
DEF 502 4G
我想找equip_name
次越过yard
的次数。
现在,我要做的是,如果equip_name
已经改变了4A to 5A or 4B to 5B, 4C to 5C till 4M to 5M and vice-versa
的码数,那么它将是horizontal crossover
其他vertical crossover
我想要的数据框是
ship_no equip_name yard Crossovers
ABC 501 4A
ABC 501 4A
ABC 501 4D Vertical
ABC 501 4D
ABC 501 4B Vertical
ABC 501 5B Horizontal
ABC 501 5C Vertical
ABC 501 5E Vertical
DEF 502 4D Vertical
DEF 502 4D
DEF 502 4C Vertical
DEF 502 5C Horizontal
DEF 502 4L Vertical
DEF 502 4G Vertical
答案 0 :(得分:2)
您可以尝试:
library(tidyverse)
d %>%
extract(yard, into = c("a","b"),'(\\d+)(\\D+)', remove = FALSE) %>%
group_by(equip_name) %>%
mutate(res=ifelse(a == lag(a), ifelse(b == lag(b), NA, "Vertical"),"Horizontal"))
Source: local data frame [10 x 6]
Groups: equip_name [2]
# A tibble: 10 x 6
ship_no equip_name yard a b res
<fctr> <int> <fctr> <chr> <chr> <chr>
1 ABC 501 4A 4 A <NA>
2 ABC 501 4A 4 A <NA>
3 ABC 501 4D 4 D Vertical
4 ABC 501 4D 4 D <NA>
5 ABC 501 4B 4 B Vertical
6 ABC 501 5B 5 B Horizontal
7 DEF 502 4D 4 D <NA>
8 DEF 502 4D 4 D <NA>
9 DEF 502 4C 4 C Vertical
10 DEF 502 5C 5 C Horizontal