Search code examples
rpurrrmagrittr

R: can I update the class of a an object in a magrittr pipe?


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")

Solution

  • 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.