Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the "code for creating a variable" from a data.frame

I have a data.frame (e.g. read from a data file using read.delim) that contains the following data:

'data.frame':   10 obs. of  3 variables:
 $ x : int  1 2 3 4 5 6 7 8 9 10
 $ y1: num  3 5 1 8 2 4 5 0 8 2
 $ y2: num  1 8 2 1 4 5 3 0 8 2

I'm now looking for a function in R, which takes the variable (data) and prints out a possible command that creates a variable like data. In this case, it should print out:

data <- data.frame(
  x=c(1:10)
  , y1=c(3,5,1,8,2,4,5,0,8,2)
  , y2=c(1,8,2,1,4,5,3,0,8,2)
)

Is there a function like this in R.

In MySQL there exists for example the command SHOW CREATE TABLE tbl_name, which

Shows the CREATE TABLE statement that creates the named table.

I'm looking for something similar for variables in R.

like image 638
R_User Avatar asked Oct 16 '13 01:10

R_User


People also ask

How do I add a variable to a Dataframe?

Variables are always added horizontally in a data frame. Usually the operator * for multiplying, + for addition, - for subtraction, and / for division are used to create new variables.

What is a variable in a data frame?

Details. A data frame is a list of variables of the same number of rows with unique row names, given class "data. frame" . If no variables are included, the row names determine the number of rows. The column names should be non-empty, and attempts to use empty names will have unsupported results.

How do you create frame data?

To create a dataframe, we need to import pandas. Dataframe can be created using dataframe() function. The dataframe() takes one or two parameters. The first one is the data which is to be filled in the dataframe table.


1 Answers

I think you are looking for dput:

> dput(data)
structure(list(x = 1:10, y1 = c(3, 5, 1, 8, 2, 4, 5, 0, 8, 2), 
    y2 = c(1, 8, 2, 1, 4, 5, 3, 0, 8, 2)), .Names = c("x", "y1", 
"y2"), row.names = c(NA, -10L), class = "data.frame")


> data0<-structure(list(x = 1:10, y1 = c(3, 5, 1, 8, 2, 4, 5, 0, 8, 2), 
+     y2 = c(1, 8, 2, 1, 4, 5, 3, 0, 8, 2)), .Names = c("x", "y1", 
+ "y2"), row.names = c(NA, -10L), class = "data.frame")
> identical(data,data0)
[1] TRUE
like image 104
mrip Avatar answered Oct 01 '22 01:10

mrip