accessing named attributes in a character vector

For some reason my head can't quite grok this named list with attributes.

I am trying to work up a tutorial on using openxlsx and I want to show how to hook a named table using the getTables function. The resulting character vector seems to have the table names as the character elements and the cell references as attributes. How would I say to R "give me the cell references for the table named 'Table1' in the following example:

library(openxlsx)

wb <- loadWorkbook("http://cerebralmastication.github.io/excel_table_data.xlsx")
gt <- getTables(wb, 'input_data')

gt
#>         J10:N22        B10:F160 
#>        "Table1" "example_table" 
#> attr(,"refs")
#> [1] "J10:N22"  "B10:F160"

str(gt)
#>  Named chr [1:2] "Table1" "example_table"
#>  - attr(*, "names")= chr [1:2] "J10:N22" "B10:F160"
#>  - attr(*, "refs")= chr [1:2] "J10:N22" "B10:F160"

The monstrosity that I cooked up to do this is:

attributes(gt[match(gt, 'Table1')])$names

but the idea of explaining that to a new learner makes me want to cry on their behalf.

How about something like this where you convert the named vector into a tibble and then do your subsetting from there?

library(openxlsx)
library(tidyverse)

wb <- loadWorkbook("http://cerebralmastication.github.io/excel_table_data.xlsx")
gt <- getTables(wb, 'input_data')

tibble(cells = names(gt), table = gt) %>%
  filter(table == "Table1") %>% 
  pull(cells)
#> [1] "J10:N22"

EDIT: Or here's another one that's pretty similar to your approach

names(grep('Table1', gt, value = TRUE))
#> [1] "J10:N22"

Created on 2018-11-04 by the reprex package (v0.2.1)

2 Likes

This is just the names of the object. The base R function to get those is base names. In base R I would do like this.

library(openxlsx)

wb <- loadWorkbook("http://cerebralmastication.github.io/excel_table_data.xlsx")
gt <- getTables(wb, 'input_data')

names(gt[gt == "Table1"])
#> [1] "J10:N22"

Created on 2018-11-04 by the reprex package (v0.2.1)

4 Likes

Oh yes, much simpler!

Thanks so much. This is exactly what I was after I just had it jumbled in my head!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.