Search code examples
rdataframehardcode

Hardcode a data frame in R


I have a data.frame object, for example the data set 'iris'. I would like to have in the script something like:

Sepal.Length_2 <- c(5.1, 4.9, 4.7, 4.6, ...)
Sepal.Width_2 <- c(3.5, 3.0, 3.2, 3.1, ...)
Petal.Length_2 <- c(1.4, 1.4, 1.3, 1.5, ...)
Petal.Width_2 <- c(0.2, 0.2, 0.2, 0.2, ...)
Species_2 <- c(setosa,setosa, setosa, setosa, ...)

iris2 <- data.frame(Sepal.Length_2, Sepal.Width_2, Petal.Length_2, Petal.Width_2)

(The reason I want achieve something like that is because I'm building a shiny app which will use data as a predefined example before introducing the own data).

I have found an interesting way using the following function:

library(stringr)
str_c(iris$Sepal.Length, sep = "", collapse = ",")

which returns:

5.1,4.9,4.7,4.6,5,5.4,4.6,5,4.4,4.9,5.4,4.8,4.8,4.3,5.8,5.7,5.4,5.1,5.7,5.1,5.4,5.1,4.6,5.1,4.8,5,5,5.2,5.2,4.7,4.8,5.4,5.2,5.5,4.9,5,5.5,4.9,4.4,5.1,5,4.5,4.4,5,5.1,4.8,5.1,4.6,5.3,5,7,6.4,6.9,5.5,6.5,5.7,6.3,4.9,6.6,5.2,5,5.9,6,6.1,5.6,6.7,5.6,5.8,6.2,5.6,5.9,6.1,6.3,6.1,6.4,6.6,6.8,6.7,6,5.7,5.5,5.5,5.8,6,5.4,6,6.7,6.3,5.6,5.5,5.5,6.1,5.8,5,5.6,5.7,5.7,6.2,5.1,5.7,6.3,5.8,7.1,6.3,6.5,7.6,4.9,7.3,6.7,7.2,6.5,6.4,6.8,5.7,5.8,6.4,6.5,7.7,7.7,6,6.9,5.6,7.7,6.3,6.7,7.2,6.2,6.1,6.4,7.2,7.4,7.9,6.4,6.3,6.1,7.7,6.3,6.4,6,6.9,6.7,6.9,5.8,6.8,6.7,6.7,6.3,6.5,6.2,5.9

so using this method it will be more easy. But the problem is with the character vectors, because they must be defined between "".

So, is there a function a method or something to get from a data frame object the data ready to hard-code in the script?


Solution

  • We can use dput to create a reproducible structure

    dput(iris)