簡體   English   中英

R:我可以在 magrittr 中更新 object 的 class 嗎?

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

我有一段代碼在其中更新了 object 的 class。 但是我必須打破以下代碼來分配 class。 是否可以優雅地分配 class 但繼續 pipe 所以我有一個 pipe 一直到最終結果? 我懷疑 {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")

當然,您可以只使用"class<-"()

library(dplyr)

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

細節

通常,在 R 中,當您可以分配給函數的 output 時,例如class(x) <- "foo" ,您使用的是“替換函數”,例如"class<-"() 可以在這里找到關於 Stack Overflow 的一個很好的討論。

使用來自 package data.tablesetattr()

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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM