我创建了一个闪亮的应用程序,用户可以在其中加载文件并将对象用作函数参数。我还打印代码以在本地运行该函数(以便我或其他任何人可以复制和粘贴以重现结果)。
我想要做的是能够使用dput
之类的东西,但是将加载对象的文本表示保存到对象而不是控制台。 dput
输出到控制台,但只返回它的第一个参数的副本。我可以使用deparse
,但是当对象的长度超过width.cutoff(默认为60和最大500)时,它会失败。
以下hacky可重复的示例说明。在其中我使用image
作为示例函数。在我的情况下,我有其他函数有更多的参数。
#create example matrices
m2 <- matrix(1:4,2,2)
m4 <- matrix(1:4,4,4)
#this is what I want to recreate
image(z=m2,col=rainbow(4))
image(z=m4,col=rainbow(4))
#convert the matrices to their text representation
txtm2 <- deparse(m2)
txtm4 <- deparse(m4)
#create a list of arguments
lArgs2 <- list( z=txtm2, col=rainbow(4) )
lArgs4 <- list( z=txtm4, col=rainbow(4) )
#construct arguments list
vArgs2 <- paste0(names(lArgs2),"=",lArgs2,", ")
vArgs4 <- paste0(names(lArgs4),"=",lArgs4,", ")
#remove final comma and space
vArgs2[length(vArgs2)] <- substr(vArgs2[length(vArgs2)],0,nchar(vArgs2[length(vArgs2)])-2)
vArgs4[length(vArgs4)] <- substr(vArgs4[length(vArgs4)],0,nchar(vArgs4[length(vArgs4)])-2)
#create the text function call
cat("image(",vArgs2,")")
cat("image(",vArgs4,")")
#the 1st one when pasted works
image( z=structure(1:4, .Dim = c(2L, 2L)), col=c("#FF0000FF", "#80FF00FF", "#00FFFFFF", "#8000FFFF") )
#the 2nd one gives an error because the object has been split across multiple lines
image( z=c("structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, ", "2L, 3L, 4L), .Dim = c(4L, 4L))"), col=c("#FF0000FF", "#80FF00FF", "#00FFFFFF", "#8000FFFF") )
#In an ideal world I would also like it to work when I did this, but maybe that's asking too much
image(z=txtm2,col=rainbow(4))
我意识到我构建函数调用的方式是一个hack,但是当我不久前看到它时,我找不到更好的方法。对任何建议开放。感谢。
答案 0 :(得分:4)
您可以执行以下操作:
## an object that you want to recreate
m2 <- matrix(1:4,2,2)
## use capture.output to save structure as a string in a varible
xx <- capture.output(dput(m2))
## recreate the object
m2_ <- eval(parse(text=xx))
image(z=m2_,col=rainbow(4))