20

Maybe I'm imagining this, but I think there is a built-in R function that lets you print an R vector (and possibly other objects like matrices and data frames) in the format that you would use to enter that object (returned as a string). E.g.,

> x <- c(1,2,3)
> x
[1] 1 2 3
> magical.function(x)
"c(1,2,3)" 

Does this function exist?

4

2 回答 2

34

dput也许?

> test <- c(1,2,3)
> dput(test)
c(1, 2, 3)

您还可以dump一次将多个对象输出到写入工作目录中的文件中:

> test2 <- matrix(1:10,nrow=2)
> test2
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    3    5    7    9
[2,]    2    4    6    8   10
> dump(c("test","test2"))

dumpdata.r然后将包含:

test <-
c(1, 2, 3)
test2 <-
structure(1:10, .Dim = c(2L, 5L))
于 2012-06-02T05:30:47.543 回答
2

我也决定添加这个解决方案,因为我发现这dput()对我想做的事情不起作用。我有一个用于根据用户会话生成报告的shiny应用程序,我在渲染我的 .Rmd 之前使用将用户参数从闪亮会话移植到 .Rmd 中。knitrknit_expand()

无需过多详细说明,我需要“按原样”移植向量,因为它们将被写入 .Rmd 中有人将运行的代码行中。对于这种情况,dput()不起作用,因为输出只吐到控制台,并且该dump()方法有效,但我不想每次都编写新文件并删除它们。

可能有更好的方法,但我编写了一个函数,它“按原样”返回向量的字符对象。它同时处理数字和字符向量(它在字符向量的每个成员周围加上引号)。它还处理单个输入并简单地返回它们。它不漂亮,我确信有更有效的方法来编写它,但它非常适合我的需要。以为我会将此解决方案添加到战斗中。

printVecAsis <- function(x) {
  ifelse(length(x) == 1, x, 
       ifelse(is.character(x), paste0("c(", paste(sapply(x, function(a) paste0("\'",a,"\'")), collapse=", "), ")"),
              paste0("c(", paste(x, collapse=", "), ")")))}
于 2016-01-03T01:57:32.190 回答