cynkra / constructive

Display Idiomatic Code to Construct Most R Objects
https://cynkra.github.io/constructive
Other
127 stars 6 forks source link

object elements named as argument names of the constructor #124

Open moodymudskipper opened 1 year ago

moodymudskipper commented 1 year ago

We had this issue for #104

How do we create a tibble with a .rows column ? how do we create a data frame with a stringsAsFactors column ? Since they should be rare (if the constructors are well designed) that's probably ok to just fall back to structure() for those.

We need in general a fall back system for corrupted objects and structure() should be the default and last fallback

moodymudskipper commented 1 year ago

As part of #51

moodymudskipper commented 1 year ago
x <- data.frame(a=1:2)
x$b <- head(cars,2)
x$stringsAsFactors <- 3:4
x$c <- 5:6
x

data.frame(
  a = 1:2, 
  c = 5:6
) |>
  (`[[<-`)("b", value = head(cars, 2)) |>
  (`[[<-`)("stringsAsFactors", value = 3:4) |>
  (`[`)(c("a", "b", "stringsAsFactors", "c"))

Or

x <- data.frame(a=1:2)
x$stringsAsFactors <- 3:4
x$b <- 5:6
x

data.frame(
  a = 1:2, 
  stringsAsFactors.1 = 3:4,
  b = 5:6
) |>
  setNames(c("a", "stringsAsFactors", "b"))
moodymudskipper commented 1 year ago

Maybe this idiom looks better, no replacement functions :

data.frame(
  a = 1:2, 
  c = 5:6
) |>
  within({
    b <- head(cars, 2)
    stringsAsFactors <- 3:4
  }) |>
  subset(select = c(a, b, stringsAsFactors, c))
moodymudskipper commented 1 year ago

This select = is interesting, it's a bit like tidy selection, we can could compress things using col1:col2 or -col1, but that's a lot of work for corner cases unless we find this idiom useful in more places.