Saturday 4 January 2020

r - How to read/import a CSV once and create code so that you don't have to read/import again




I have an R script that I would like to share with people, but it currently depends on reading many separate csv files into data frames in order to run. I’m wondering if there’s any quick and easy way to read the csv files and then create the lines of code to create the data frame without having to read external files in the future (I have dozens of csv files with hundreds of records each, but I only want to share the .R file).



As an example, I currently have:



> species <- read.csv("species.csv")
> species

SpeciesID ScientificName Mortality
1 11 Acer_platanoides 2.27
2 57 Gleditsia_triacanthos 1.33
3 132 Tilia_cordata 1.33
4 1 Abies_balsamea 3.33


After reading the csv databases once, I would like to create the code so that I don’t have to read the csv again (and so that I can send people one R script and not an R script with dozens of other files).



So, can the above somehow lead to the following, without having to write it all out manually?? Thank you.




> species <- data.frame("SpeciesID" = c(11, 57, 132, 1),
+ "ScientificName" = c("Acer_platanoides", "Gleditsia_triacanthos", "Tilia_cordata", "Abies_balsamea"),
+ "Mortality" = c(2.27, 1.33, 1.33, 3.34))
> species
SpeciesID ScientificName Mortality
1 11 Acer_platanoides 2.27
2 57 Gleditsia_triacanthos 1.33
3 132 Tilia_cordata 1.33
4 1 Abies_balsamea 3.34


Answer



Sounds like what you need to do to create a reproducible example. Following Joris Meys' solution dput() makes it pretty easy.



An example from the linked solution:



> dput(head(iris,4))
structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6), Sepal.Width = c(3.5,
3, 3.2, 3.1), Petal.Length = c(1.4, 1.4, 1.3, 1.5), Petal.Width = c(0.2,
0.2, 0.2, 0.2), Species = structure(c(1L, 1L, 1L, 1L), .Label = c("setosa",

"versicolor", "virginica"), class = "factor")), .Names = c("Sepal.Length",
"Sepal.Width", "Petal.Length", "Petal.Width", "Species"), row.names = c(NA,
4L), class = "data.frame")

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...