gpt4 book ai didi

r - 输入一个 S4 对象

转载 作者:行者123 更新时间:2023-12-04 06:49:02 25 4
gpt4 key购买 nike

一个人会怎样dput() S4 对象?我试过这个

require(sp)
require(splancs)
plot(0, 0, xlim = c(-100, 100), ylim = c(-100, 100))
poly.d <- getpoly() #draw a pretty polygon - PRETTY!
poly.d <- rbind(poly.d, poly.d[1,]) # close the polygon because of Polygons() and its kin
poly.d <- SpatialPolygons(list(Polygons(list(Polygon(poly.d)), ID = 1)))
poly.d
dput(poly.d)

请注意,如果我 dput() S4 对象,我无法再次重建它。你的意见?

最佳答案

按照目前的情况,您不能 dput这个对象。 dput的代码包含以下循环:

if (isS4(x)) {
cat("new(\"", class(x), "\"\n", file = file, sep = "")
for (n in slotNames(x)) {
cat(" ,", n, "= ", file = file)
dput(slot(x, n), file = file, control = control)
}
cat(")\n", file = file)
invisible()
}

这以递归方式处理 S4 对象,但它依赖于 S3 对象不包含 S4 对象的假设,在您的示例中不包含:
> isS4(slot(poly.d,'polygons'))
[1] FALSE
> isS4(slot(poly.d,'polygons')[[1]])
[1] TRUE

编辑:这是解决 dput 的限制的方法。 .它适用于您提供的示例,但我认为它不会在一般情况下起作用(例如,它不处理属性)。
dput2 <- function (x,
file = "",
control = c("keepNA", "keepInteger", "showAttributes")){
if (is.character(file))
if (nzchar(file)) {
file <- file(file, "wt")
on.exit(close(file))
}
else file <- stdout()
opts <- .deparseOpts(control)
if (isS4(x)) {
cat("new(\"", class(x), "\"\n", file = file, sep = "")
for (n in slotNames(x)) {
cat(" ,", n, "= ", file = file)
dput2(slot(x, n), file = file, control = control)
}
cat(")\n", file = file)
invisible()
} else if(length(grep('@',capture.output(str(x)))) > 0){
if(is.list(x)){
cat("list(\n", file = file, sep = "")
for (i in 1:length(x)) {
if(!is.null(names(x))){
n <- names(x)[i]
if(n != ''){
cat(" ,", n, "= ", file = file)
}
}
dput2(x[[i]], file = file, control = control)
}
cat(")\n", file = file)
invisible()
} else {
stop('S4 objects are only handled if they are contained within an S4 object or a list object')
}
}
else .Internal(dput(x, file, opts))
}

这是在行动:
> dput2(poly.d,file=(tempFile <- tempfile()))
> poly.d2 <- dget(tempFile)
> all.equal(poly.d,poly.d2)
[1] TRUE

关于r - 输入一个 S4 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3466599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com