Home > database >  Get dput data assigned to variable
Get dput data assigned to variable

Time:05-07

When I try to assign dput to object, it assigns and then prints the values below. It should ne happen.It should just pass to the object

get_ls <- dput(head(iris))
structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6, 5, 5.4), 
    Sepal.Width = c(3.5, 3, 3.2, 3.1, 3.6, 3.9), Petal.Length = c(1.4, 
    1.4, 1.3, 1.5, 1.4, 1.7), Petal.Width = c(0.2, 0.2, 0.2, 
    0.2, 0.2, 0.4), Species = structure(c(1L, 1L, 1L, 1L, 1L, 
    1L), .Label = c("setosa", "versicolor", "virginica"), class = "factor")), row.names = c(NA, 
6L), class = "data.frame")

Expected output

get_ls <- dput(head(iris))
get_ls
structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6, 5, 5.4), 
    Sepal.Width = c(3.5, 3, 3.2, 3.1, 3.6, 3.9), Petal.Length = c(1.4, 
    1.4, 1.3, 1.5, 1.4, 1.7), Petal.Width = c(0.2, 0.2, 0.2, 
    0.2, 0.2, 0.4), Species = structure(c(1L, 1L, 1L, 1L, 1L, 
    1L), .Label = c("setosa", "versicolor", "virginica"), class = "factor")), row.names = c(NA, 
6L), class = "data.frame")

CodePudding user response:

You can write a new function to extract the call printed by dput().

dput.call <- function(x) {
  parse(text = capture.output(dput(x)))[[1]]
}

get_ls <- dput.call(head(iris))
get_ls
# structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6, 5, 5.4), 
#     Sepal.Width = c(3.5, 3, 3.2, 3.1, 3.6, 3.9), Petal.Length = c(1.4, 
#         1.4, 1.3, 1.5, 1.4, 1.7), Petal.Width = c(0.2, 0.2, 0.2, 
#         0.2, 0.2, 0.4), Species = structure(c(1L, 1L, 1L, 1L, 
#         1L, 1L), .Label = c("setosa", "versicolor", "virginica"), 
#         class = "factor")), row.names = c(NA, 6L), class = "data.frame")

class(get_ls)
# [1] "call"

CodePudding user response:

Is this what you are after:

con <- file() # new connect
dput(mtcars, con) # dump the dput in the connection
readLines(con) # read it as a vector
  •  Tags:  
  • r
  • Related