Skip to content

Commit 66cb857

Browse files
committed
✏️ Add I() note
1 parent d308f49 commit 66cb857

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

r-code.qmd

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,36 @@ writexl::write_xlsx(diamonds_split, path = "diamonds_by_cut.xlsx")
1212
- `split()`: Splits the dataset into a list of data frames by cut. The names of the list (Ideal, Premium, etc.) become the sheet names automatically.
1313
- `write_xlsx()`: Takes the list and writes each element to a separate sheet in a single Excel file.
1414

15-
Each sheet will correspond to a different diamond cut (Ideal, Premium, Good, Very Good, Fair).
15+
Each sheet will correspond to a different diamond cut (Ideal, Premium, Good, Very Good, Fair).
16+
17+
18+
## Using `I()` to Force JSON Arrays
19+
20+
### The Problem
21+
- Had a tibble that I converted to a named list for JSON export
22+
- Used `jsonlite::toJSON()` with `auto_unbox = TRUE` (needed for other fields)
23+
- Single-element vectors were being converted to scalars: `"level_down": "ey52"`
24+
- My JSON schema required ALL values to be arrays: `"level_down": ["ey52"]`
25+
- Multi-element vectors worked fine, only single values broke
26+
27+
### The Solution
28+
29+
Wrapping them with `I()` forced them to stay as arrays
30+
31+
```r
32+
selections |>
33+
dplyr::filter(.data$choice != "no_change") |>
34+
dplyr::group_by(.data$choice) |>
35+
dplyr::summarise(hrg_codes = list(.data$hrg_code)) |>
36+
tibble::deframe() |>
37+
purrr::map(I) # <- This is the magic
38+
```
39+
40+
Note that `I()` has to be applied after `deframe()`
41+
42+
### What is `I()`?
43+
44+
- Stands for "AsIs" - it's a class wrapper
45+
- Tells R: "don't mess with this, keep it as-is"
46+
- In {jsonlite}: protects vectors from unboxing even when `auto_unbox = TRUE`
47+
- In data frames: prevents lists from being simplified when subsetting

0 commit comments

Comments
 (0)