[英]How to I write an S3 extract method [ in r
我有一個名為 gfe_obj 的數據框,其結構如下:
我想寫一個提取 function 這樣當我運行下面的代碼時,我得到相應的 output:
目前,我有:
str(gfe_obj)
'[.gfe_obj' <- function(x,i) {
class(x) <- "gfe"
as.gfe_obj(x[i])
}
sub_gfe_obj <- gfe_obj[1:3]
str(sub_gfe_obj)
但是當我運行這段代碼時,我在 as.gfe_obj(x[i]) 中出現錯誤:找不到 function "as.gfe_obj"。
我引用了從這里編寫的方法: How to implement extracting/subsetting ([, [<-, [[, [[<-) functions for custom S3 classes?
謝謝您的幫助。
我不確定你的gfe
class 的確切結構應該是什么,但假設它是一個由兩個對象組成的列表(一個名為frames
的 3D 數組和一個名為info
的數據幀,其行數與第三維相同的frames
,那么您的 S3 方法將是:
`[.gfe`<- function(x, i) {
x$frames <- x$frames[,,i]
x$info <- x$info[i,]
x
}
為了測試這一點,我需要一個模擬 class 構造函數和一些虛擬數據:
gfe <- function(frames, info) {
structure(list(frames = frames, info = info), class = "gfe")
}
gfe_obj <- gfe(frames = array(1:90, dim = c(3, 3, 10)),
info = data.frame(x = 1:10, y = letters[1:10]))
str(gfe_obj)
#> List of 2
#> $ frames: int [1:3, 1:3, 1:10] 1 2 3 4 5 6 7 8 9 10 ...
#> $ info :'data.frame': 10 obs. of 2 variables:
#> ..$ x: int [1:10] 1 2 3 4 5 6 7 8 9 10
#> ..$ y: chr [1:10] "a" "b" "c" "d" ...
#> - attr(*, "class")= chr "gfe"
現在我們可以看到提取器方法按預期工作:
sub_gfe_obj <- gfe_obj[2:3]
str(sub_gfe_obj)
#> List of 2
#> $ frames: int [1:3, 1:3, 1:2] 10 11 12 13 14 15 16 17 18 19 ...
#> $ info :'data.frame': 2 obs. of 2 variables:
#> ..$ x: int [1:2] 2 3
#> ..$ y: chr [1:2] "b" "c"
#> - attr(*, "class")= chr "gfe"
使用reprex v2.0.2創建於 2022-09-25
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.