Introduction to R and Graphics

Transcription

Introduction to R and Graphics
Examples of graphs in R
Examples of Graphs in R
Example of Graphs in R
Example of Graphs in R
Introduction to R
 Change the working directory in R
 1) through the menu
 In Windows: go to the File menu, select Change
Working Directory, and select the appropriate
folder/directory
 In Macs: go to the Misc menu, select Change Working
Directory, and select the appropriate folder/directory
Introduction to R
 2) by using the function: setwd("...")
 setwd("C:/Users/User Name/Documents/FOLDER")
 You can check that your working directory has been
correctly set by using the function:
 getwd()
Installing using a package in R
 Go to packages.
 Choose install packages.
 Choose Vietnam.
 And choose the package that you will need to install.
 library(xlsx).
Read txt files into R
 > mydata <- read.table("mydata.txt") # read text file
> mydata
V1 V2 V3
1 100 a1 b1
2 200 a2 b2
3 300 a3 b3
4 400 a4 b4
# print data frame
Read CSV files into R
 > mydata <- read.csv("mydata.csv") # read csv file
> mydata
Col1 Col2 Col3
1 100 a1 b1
2 200 a2 b2
3 300 a3 b3
Read SAS data into R
 # save SAS dataset in trasport format
libname out xport 'c:/mydata.xpt';
data out.mydata;
set sasuser.mydata;
run;
# in R
library(Hmisc)
mydata <- sasxport.get("c:/mydata.xpt")
# character variables are converted to R factors
Basic Data Management in R
 # save SPSS dataset in trasport format
get file='c:\mydata.sav'.
export outfile='c:\mydata.por'.
# in R
library(Hmisc)
mydata <- spss.get("c:/mydata.por",
use.value.labels=TRUE)
# last option converts value labels to R factors
Basic Data Management in R
 # read in the first worksheet from the workbook
myexcel.xlsx
# first row contains variable names
library(xlsx)
mydata <- read.xlsx("c:/myexcel.xlsx", 1)
# read in the worksheet named mysheet
mydata <- read.xlsx("c:/myexcel.xlsx", sheetName =
"mysheet")
Read Stata files into R
 # input Stata file
library(foreign)
mydata <- read.dta("c:/mydata.dta")
Export data into .txt file
 write.table(mydata, "c:/mydata.txt", sep="\t")
Export data to Excel Spreadsheet
 library(xlsx)
write.xlsx(mydata, "c:/mydata.xlsx")
Export data to SPSS
 # write out text datafile and
# an SPSS program to read it
library(foreign)
write.foreign(mydata, "c:/mydata.txt",
"c:/mydata.sps", package="SPSS")
Export data to SAS
 # write out text datafile and
# an SAS program to read it
library(foreign)
write.foreign(mydata, "c:/mydata.txt",
"c:/mydata.sas", package="SAS")
Export data to Stata
 # export data frame to Stata binary format
library(foreign)
write.dta(mydata, "c:/mydata.dta")