質問

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.

役に立ちましたか?

解決

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

他のヒント

dput is the base function that you are likely looking for.
I use a wrapper function, reproduce which I've shared on the "How to make a reproducible example" question.

# install.packages("devtools")
library(devtools)
source_url("https://raw.github.com/rsaporta/pubR/gitbranch/reproduce.R")

reproduce(myData, whole=TRUE)

Which gives:

 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") 

You can also output select rows, columns, etc or a percentage of them.

For further explanation of the function, please have a look at the r faq question

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top