Skip to content

Commit 4565fc1

Browse files
committed
✏️ Add I() note
1 parent d308f49 commit 4565fc1

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

r-code.qmd

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,35 @@ 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::group_by(.data$choice) |>
34+
dplyr::summarise(hrg_codes = list(.data$hrg_code)) |>
35+
tibble::deframe() |>
36+
purrr::map(I) # <- This is the magic
37+
```
38+
39+
Note that `I()` has to be applied after `deframe()`
40+
41+
### What is `I()`?
42+
43+
- Stands for "AsIs" - it's a class wrapper
44+
- Tells R: "don't mess with this, keep it as-is"
45+
- In {jsonlite}: protects vectors from unboxing even when `auto_unbox = TRUE`
46+
- In data frames: prevents lists from being simplified when subsetting

0 commit comments

Comments
 (0)