constructive icon indicating copy to clipboard operation
constructive copied to clipboard

object elements named as argument names of the constructor

Open moodymudskipper opened this issue 1 year ago • 4 comments

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 avatar Apr 02 '23 16:04 moodymudskipper

As part of #51

moodymudskipper avatar Apr 02 '23 16:04 moodymudskipper

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 avatar May 05 '23 13:05 moodymudskipper

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 avatar May 06 '23 16:05 moodymudskipper

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.

moodymudskipper avatar May 06 '23 17:05 moodymudskipper