如何在r

时间:2017-08-01 12:38:32

标签: r

我在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   

1 个答案:

答案 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