Skip to content

set variable type #45

@einarhjorleifsson

Description

@einarhjorleifsson

Would it be possible to have an option in the function to set the variable type within the icesDatras function calls?

Part of the reason:

library(icesDatras)
library(dplyr)
hl1 <- icesDatras::getDATRAS(record = "HL", survey = "NS-IBTS", year = 2025, quarter = 1)
hl2 <- icesDatras::getDATRAS(record = "HL", survey = "ROCKALL", year = 2001, quarter = 3)
rbind(hl1, hl2)   # no error
bind_rows(hl1, hl2) # error
Error in `bind_rows():
  ! Cant combine `..1$GearEx` <character> and `..2$GearEx` <integer>.

I solve this by (use dplyr, so this works within RDB/SQL framework)

dr_settypes <- function(d) {

  key_int <- dr_coltypes |> dplyr::filter(type == "int") |> dplyr::pull(field) |> unique()
  key_dbl <- dr_coltypes |> dplyr::filter(type == "dbl") |> dplyr::pull(field) |> unique()

  d <-
    d |>
    dplyr::mutate(dplyr::across(dplyr::everything(),    as.character))  |>
    dplyr::mutate(dplyr::across(dplyr::any_of(key_int), as.integer))  |>
    dplyr::mutate(dplyr::across(dplyr::any_of(key_dbl), as.numeric))

  return(d)

}

dr_settypes uses a lookup table (dr_coltypes), looks something like this:

dr_coltypes
# A tibble: 159 × 3
   field      type  record
   <chr>      <chr> <chr> 
 1 RecordType chr   HH    
 2 Quarter    int   HH    
 3 Country    chr   HH    
 4 Ship       chr   HH    
 5 Gear       chr   HH    
 6 SweepLngt  int   HH    
 7 GearEx     chr   HH    
 8 DoorType   chr   HH    
 9 StNo       chr   HH    
10 HaulNo     int   HH 

Then this works:

bind_rows(hl1 |> dr_settypes(),
          hl2 |> dr_settypes())

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions