Reading Files into and out of R

You, R
Back

Video Here: https://www.youtube.com/watch?v=ibkBTqx3LW8

The following code shows how to read a .CSV/.XLSX file into R, perform a manipulation, and write a new file out of R.

#Clears environment
rm(list = ls(all.names = TRUE))
#-------------------------------------------------------------------
#-----------------------------LIBRARIES-----------------------------
#-------------------------------------------------------------------
library(readxl)
library(dplyr)
library(writexl)
#-------------------------------------------------------------------
#---------------------------DATA SOURCES----------------------------
#-------------------------------------------------------------------
#Set your working directory
wd <- "C:/[YOUR PATH]"
#Set path to an Excel file
excelFile <- paste(wd, "input.xlsx", sep='')
#Set path to a CSV file
csvFile <- paste(wd, "input.csv", sep='')
#Read Excel file into R and view it
rawExcel <- read_excel(excelFile)
View(rawExcel)
#Read CSV file into R and view it
rawCSV <- read.csv(csvFile)
View(rawCSV)
#-------------------------------------------------------------------
#------------------------DATA MANIPULATION--------------------------
#-------------------------------------------------------------------
#Add a pay raise column equal to 5% of base Salary
df <- rawExcel %>%
  mutate(rawExcel, "Pay Raise" = rawExcel$`Base Salary` * .05)
View(df)
#-------------------------------------------------------------------
#-------------------------OUTPUT NEW FILE---------------------------
#-------------------------------------------------------------------
#Set path to write Excel file
excelOut <- paste(wd, "output.xlsx", sep = '')
#Set path to write CSV file
csvOut <- paste(wd, "output.csv", sep = '')
#Write Excel file
write_xlsx(df, excelOut)
#Write CSV file
write.csv(df, csvOut, row.names = T)
© Trevor French.RSS