03.
Code_AOC_Vector (2)
rm (list=ls(all=TRUE))
# Relational operations----
# Case1: when length(k)=1
# Numeric
x <- seq (from= - 1 , to= 1 , by= 1 ); x
x<0
x>0
x == 0
x <= 0
x >= 0
x != 0
# character
x<-c("A","B","C");x
x==c("A")
# Case 2: length(k)=length(x)
x <- seq (from= - 1 , to= 1 , by= 1 ); x
k <- seq (from= 0 , to= 2 , by= 1 ); k
length(x)
length(k)
x<k
x>k
x == k
x <= k
x >= k
x != k
# Case 3: a mismatch in length between x and k.
# example 1:length(x)>length(k)
x <- c(1,2,3,4);x
k <- c(1,2);k
x == k
1
# example 2:length(x)<length(k)
x <- c(4,5);x
k <- c(4,5,6,7);k
x == k
# Logical operations----
x <- c(1,2,4,6); x
y <- c(5,6,7,8); y
(x < 4)
(y < 4)
# Logical and operation
(x<4)&(y<4)
# Logical or operation
(x < 4) | (y < 4)
# Logical not operation
!(x > 4)
# operation order
x <- 3 ; y <- - 3
(x > 2) & (y < 2) |( (x + y) != 3 )
# Positive integer index vector ----
x<-c("A", "B","C", "D", "E")
x[2]
x[3:5]
x[c(1,3,5)]
x[rep(c(1,3,5), times=3)]
# Negative integer index vector ----
x<-c("A", "B","C", "D", "E")
x[-(1:3)]
x[-c(1,3,5)]
2
# Logical index vector ----
x <- c ( 1 , 3 , 5 )
x[ c ( TRUE , FALSE , TRUE )]
y <- c ( 1 : 10 );y
y[(y > 5 )]
y[(y != 5 )]
z <- c ( "A" , "B" , "C" )
z[(z == "B" )]
# Character index vector ----
x <- c ( 80 , 90 , 99 , 50 )
names(x) <- paste0("Price0",c(1:4)); x
x[c("Price01","Price03" )]
# Replace the element values----
x<-c(5, 10, 1, 20);x
x[c(2,4)]<-1;x
# replace elements at positions 2 and 4 with 1 and 1, respectively.
y<-c(5, 10, 1, 20);y
y[c(2,4)]<-c(2,3);y
# Replace elements at positions 2 and 4 with 2 and 3, respectively.
z<-c(5, 10, 11, 20);z
z[c(TRUE,FALSE,FALSE,TRUE)]<-c(9,12);z
# Replace elements at positions 1 and 4 with 9 and 12, respectively.
# which.min() and which.max()----
x <- c ( 5 , 10 , 1 , 20 , 10, 1,12 )
which.min(x)
which.max(x)
3
# which()----
# EX01
x <- c ( 5 , 10 , 1 , 20 , 20 , 10 );x
which (x==1)
which (x==10)
which (x>10)
which ((x>10)&(x<25))
# EX02
y <- c ( "Paul" , "Andy" , "Judy" , "Lucy", "Andy" );y
which (y=="Andy")
which ((y=="Andy")|(y=="Paul"))
# EX03
x <- c ( 5 , 10 , 1 , 12 , 10, 1,12 )
which.min(x)
which(x==min(x))
which.max(x)
which(x== max (x))
# EX04
z<-sqrt(c(1:100)*0.5)
a<-which((z>6)&(z<7));a
z[a]
4
# cat()----
#EX01:
cat ("x=", 5)
cat ("x=", 5, sep = "" ) # sep = "" : no spaces
# EX02
x <- 2 ; y <- x + 4 ; z <- x * y
cat ("x=" ,x, "x+4=" ,y, "z=" ,z)
cat ("x=" ,x, "\n" , "x+4=" ,y, "\n" , "z=" ,z) #newline : "\n"
cat ("x=" ,x, "\n" , "x+4=" ,y, "\n" , "z=" ,z,sep="") #newline and no spaces