Question Details

No question body available.

Tags

r tidyr

Answers (4)

July 21, 2026 Score: 2 Rep: 79,216 Quality: Medium Completeness: 80%

The solutions below are 2 orders of magnitude faster and need much less memory.

original bindrows(dftoadd) } ) |> bindrows() |> select(-z) |> dropna() }

rui1 dropna() rui2 na.omit()

bench::mark(original(), rui1(), rui2(), col(), check = FALSE) #> # A tibble: 4 × 6 #> expression min median itr/sec memalloc gc/sec #> #> 1 original() 14.5ms 15.3ms 62.1 1.99MB 9.55 #> 2 rui1() 314.9µs 353.8µs 2590. 47.66KB 8.43 #> 3 rui2() 201.2µs 238µs 3712. 26.06KB 10.4

library(microbenchmark) microbenchmark(original(), rui1(), rui2()) |> print(order = "median") #> Unit: microseconds #> expr min lq mean median uq max neval cld #> rui2() 224.5 275.40 325.794 306.30 346.75 683.5 100 b #> rui1() 334.9 363.35 465.796 398.15 462.80 3173.3 100 b #> original() 13254.1 14440.80 16645.104 14879.60 17207.40 66733.8 100 a

Created on 2026-07-21 with reprex v2.1.1

When run outside reprex I get much less memory use, rui1 only 216B and rui2 0B.


I also tried timing with bigger data and the results were comparable to the results above. For instance, with a data set with 5000+ rows.

ex
backup
July 21, 2026 Score: 2 Rep: 13,440 Quality: Medium Completeness: 60%

You can unnest and preserve the row_id. Then set ord = 1 for the unnested, and ord = 0 for the normal columns, then order by both. For 500k rows, this takes ~80 ms.

library(tibble)

ex = tibble( x = c("A", "B", "C", "D", "E"), y = 1:5, z = list(tibble(x = "A2", y = 1.5), NA, NA, tibble(x = "D2", y = 4.5), NA) )

ex2
July 21, 2026 Score: 2 Rep: 106,421 Quality: Low Completeness: 40%

You can try

id
July 21, 2026 Score: 2 Rep: 7,578 Quality: Low Completeness: 50%

using {data.table}:

library(data.table)

ex setkey(id)

datatablesolution ## rowbind them all: rbindlist() |> ## order by row id (tibbles coming last): [order(id), -c("id")] }

somewhat slower than Rui Barradas' solutions:

+ Unit: nanoseconds expr min lq mean median uq max neval rui1 14 15 19.12 16 16 373 100 rui2 15 16 19.83 17 19 274 100 datatable_solution 14 15 21.42 16 16 592 100