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

痞子三分冷 提交于 2021-02-11 15:54:02

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!