1

I have a piece of code where I update the class of the object. But I have to break the follow of the code to assign the class. Is there an elegant to to assign the class but continue the pipe so I have one pipe all the way to the final result? I suspect there might be something in {purrr}?

library(disk.frame)
library(dplyr)
library(tidyquery)

a = nycflights13::airports %>%
  as.disk.frame

class(a) <- c(class(a), "data.frame")

a %>% 
  query("SELECT name, lat, lon ORDER BY lat DESC LIMIT 5")
xiaodai
  • 14,889
  • 18
  • 76
  • 140

2 Answers2

7

Sure, you can just use "class<-"():

library(dplyr)

x <- 1:10 %>%
    "class<-"("foo")
x
#  [1]  1  2  3  4  5  6  7  8  9 10
# attr(,"class")
# [1] "foo"

Details

Generally, in R, when you can assign to a function's output, e.g. class(x) <- "foo", what you're using is a "replacement function", e.g. "class<-"(). A good discussion of this on Stack Overflow can be found here.

duckmayr
  • 16,303
  • 3
  • 35
  • 53
2

Using setattr() from package data.table:

library(data.table)
x <- 1:10
x %>% setattr("class", c(class(x), "xiaodai's special"))
x

 [1]  1  2  3  4  5  6  7  8  9 10
attr(,"class")
[1] "integer"           "xiaodai's special"
s_baldur
  • 29,441
  • 4
  • 36
  • 69