TA week2

Alex

2018/03/22

Outline

  • Data Frame in R
  • Data Input and Output with R
  • Basic Logical Operators

Data Frame in R

What is DataFrame

  • one of the main tools for data analysis with R
  • multiple types of data (more general than matrices)

Basic Operation

  • dim()
  • nrow()
  • ncol()
  • ...
  • str()
  • summary()

Data Input and Output with R

Input .csv file

  • read.csv(file_path)
  • read.table(file_path)
  • fread(file_path)
  • watchout your path!

Input excel file

  • install the package (open as admin)
    • install.packages('readxl',repos="http://cran.rstudio.com/")
    • ​library(readxl)
  • excel_sheets(file)
  • read_excel(file, sheet = sheet)

Output to csv

write.csv(df, file = file_name)

Output to excel

  1. install package "xlsx"
  2. install java for 64 bit
Sys.setenv(JAVA_HOME='C:\\Program Files\\Java\\jre7') # for 64-bit version
Sys.setenv(JAVA_HOME='C:\\Program Files (x86)\\Java\\jre7') # for 32-bit version
library(xlsx)

write.xlsx(df, file = file_name)

Logical Operators and Control Flow

Logical Operators

  • ==
  • !=
  • >=
  • <=
  • >
  • <
  • %in%
  • &
  • |
  • &&
  • ||

Control Flow (1/3) - if else

if (condition) {
    # do something ...
}

if (cond.) {
    # do something ...
} else {
    # do the other ...
}

if (cond.) {
    # do something ...
} else if (cond. 2) {
    # do another ...
} else if (cond. 3) {
    # do another ...
} else {
    # do another ...
}

if (condition) { ... } [ else if ] ... [ else ]

Control Flow (2/3) - while

while (condition) {
    # do something ...
}

while (condition) {
    # do something ...
    ...
    break
}

while (condition) { ... }

Control Flow (3/3) - for

my_vec <- c(1,2,3,4,5)
for (temp_var in vec){
    print(temp_var)
}
for (i in 1:length(vec)){
    print(vec[i])
}

for ( ... ) {
    ...
    break
    ...
    next
}

for (temporary_variable in object) { ... }

something cool

  • ifelse
  • function
  • apply
  • pipe
  • mode() vs typeof() vs class()

888888888888888

R_Basic_week2

By a136489

R_Basic_week2

  • 623