####
#
# 02B Advanced indexing techniques
#
####

cars <- c("BMW","Audi","VW")
type <- c("3","A4","Passat") 
price <- c(1200000,1164000,950500)
consumption <- c(6.2,5.9,5.9)

df <- data.frame(cars,type,price,consumption, stringsAsFactors = F) 

#
# Selecting: indexes
#

vect <- c(2, 6, 9) 
str(vect) 

vect[3]

vect[[3]]

vect[1:3]

vect[[1:3]]

#
# Selecting: indexes of nested objects - list
#

ls <- list(c(0,1,2,3), 
           c("car","bike"),
           "single object")

ls[2]

class(ls[2])

ls[[2]]

class(ls[[2]])

ls[[2]][2]

ls[2:3]

ls[[2:3]]

#
# Advanced use of indexes: logical statement
#

vect <- c(2, 6, 9)

vect == 9

index <- vect == 9

vect[index]


#
# Advanced use of indexes: function results
#

vect.na <- c(1,0,1,2,2,NA,NA,2,1) 

is.na(vect.na)

index <- is.na(vect.na)

vect.na[index]

index.o1 <- !is.na(vect.na) # option 1

vect.na[index.o1]

index.o2 <- is.na(vect.na) == FALSE # option 2

vect.na[index.o2]

index <- !is.na(vect.na) & vect.na >= 1.5 

vect.na[index]

index <- is.na(vect.na) | vect.na >= 1.5

vect.na[index]

#
# Advanced use of indexes: logical tests on data frames
#

df[,3]

df[,3] > 1000000

df

df[ ,3,drop = FALSE] > 1000000 # just a demonstration

condition <- df[,3] > 1000000

df[condition,]

df.sub <- df[condition,]

#
# Advanced use of indexes: logical tests on data frames - variable name
#

df$price > 1000000

condition <- df$price > 1000000

df[condition,]

df.sub <- df[condition,]

#
# Advanced use of indexes: logical tests on data frames - direct use of conditions
#

df[ df$price > 1000000 ,  ]

df[ df[ ,3] > 1000000 ,  ]

#
# Advanced use of indexes: logical tests on data frames - combinations
# 

df[,3] > 1000000

condition <- df[ ,3] > 1000000

df[ condition , 1 ]

df[ condition , "consumption" ]

#
# Advanced use of indexes: logical tests on data frames - straightforward approach does not work
#

df$cars == c( "BMW" , "Audi" )

#
# Advanced use of indexes: logical tests on data frames - using AND/OR operators
#

df$cars == "BMW" | df$cars == "Audi"

condition <- df$cars == "BMW" | df$cars == "Audi"

df[condition,]

#
# Advanced use of indexes: logical tests on data frames - using special %in% operator
#

df$cars %in% c( "BMW" , "Audi" )

condition <- df$cars %in% c( "BMW" , "Audi" )

df[condition,]

#
# Advanced use of indexes: ordering data frame
#

order(df$cars)

condition <- order(df$cars)

df[condition,]

df.ord <- df[condition,]