Chapter 2 Introduction: R Basics
For the love of God before you do anything, familiarize yourself with R Projects and the here
package. These make R so much more user friendly and less of a nightmare. If you need an overview, go here: http://jenrichmond.rbind.io/post/how-to-use-the-here-package/
Now lets get stuck in.
library(tidyverse)
2.1 Importing Data
2.1.1 Spreadsheets
See https://nacnudus.github.io/spreadsheet-munging-strategies/index.html for more detailed and in-depth tutorials (if you need that kind of thing)
2.2 Exporting (i.e., saving) Data and Output
2.2.1 Exporting to .CSV
Generally speaking, unless you have a specific reason to, don’t. But if you must: write_csv()
2.2.2 Export to .RData (and load the data again later)
save(obj_name, file=here::here("subfolder", "save_file_name"), compress = FALSE)
load(here::here("folder", "save_name.RData"))
2.2.3 Export to Excel
library(openxlsx)
#Method 1: If you only want to export 1 thing, and/or only need output document
#write as object, with no formatting:
write.xlsx(objectname,file = "filenamehere.xlsx",colnames=TRUE, borders="columns")
#write as table:
write.xlsx(objectname,"filename.xlsx",asTable = TRUE)
#Method 2: If you want to do the above, but add multiple objects or tables to one workbook/file:
## first Create Workbook object
<- createWorkbook("AuthorName")
wb #then add worksheets (as many as desired)
addWorksheet(wb, "worksheetnamehere")
#then write the object to the worksheet
writeData(wb, "test", nameofobjectordataframe, startCol = 2, startRow = 3, rowNames = TRUE)
#save excel file
saveWorkbook(wb, "filenamehere.xlsx", overwrite =TRUE)
#Method 3: exact same as method 2, but creating a more fancy tables
<- createWorkbook("Ryan")
wb addWorksheet(wb, "worksheetnamehere")
writeDataTable(wb, sheetName, objectName, startCol = 1, startRow = 1, colNames = TRUE, rowNames = FALSE,
tableStyle="TableStyleLight2",tableName=NULL, headerStyle = NULL,withFilter=FALSE,keepNA=TRUE,sep=", ",
stack = FALSE, firstColumn = FALSE, lastColumn = FALSE,bandedRows = TRUE,bandedCols = FALSE)
saveWorkbook(wb, "filenamehere.xlsx", overwrite =TRUE)
2.2.4 Access/edit specific cell number values
=tibble::tribble(~Color,
rainbow"red",
"orange",
"black",
"green",
"blue",
"purple")
$Color[3] # access, but can't overwrite this way rainbow
## [1] "black"
3,"Color"] # access and can overwrite rainbow[
## # A tibble: 1 x 1
## Color
## <chr>
## 1 black
3, "Color"]= "yellow" # save this value to row 3 in column "Color"
rainbow[
rainbow
## # A tibble: 6 x 1
## Color
## <chr>
## 1 red
## 2 orange
## 3 yellow
## 4 green
## 5 blue
## 6 purple