问题
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")
回答1:
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.
回答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"
来源:https://stackoverflow.com/questions/58539609/r-can-i-update-the-class-of-a-an-object-in-a-magrittr-pipe