Site icon R-bloggers

Reading Files into and out of R

[This article was first published on R in Trevor French on Medium, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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)

Reading Files into and out of R was originally published in Trevor French on Medium, where people are continuing the conversation by highlighting and responding to this story.

To leave a comment for the author, please follow the link and comment on their blog: R in Trevor French on Medium.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.