Short answer – create a reproducible R data frame with function dput. Dput will give you a good reproducible piece of code that you can use for examples.
Here are the first rows of the iris data set. Imagine that you are interested to turn it into code to share with others.
head(iris) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species #1 5.1 3.5 1.4 0.2 setosa #2 4.9 3.0 1.4 0.2 setosa #3 4.7 3.2 1.3 0.2 setosa #4 4.6 3.1 1.5 0.2 setosa #5 5.0 3.6 1.4 0.2 setosa #6 5.4 3.9 1.7 0.4 setosa
Here is the easy reproducible version R data frame with the first rows of iris by using dput.
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")
After you copy data frame interpretation in R code, the result might look messy. Use the shortcut Ctrl + Shift + A in RStudio to reflow your code.
hiris <- 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" )
If you found that useful, please take a look at my favorite RStudio tips and tricks.
Create R data frame from scratch
Here is another example that might be handy for experienced Excel users. How to create R data frame from scratch by using Excel.
Create an empty R data frame
Sometimes you might want to create just an empty R data frame. That is useful to combine with other data and ensure that there always be a data frame with certain column names.
Leave a Reply