x<-c(2,3,4) #### Common Commands ####
str(x) # str() tell what the variable are defined as or recognised as in R # str(x), shows that x is vector of dim 1x3 with numerical elements
typeof(x) Y<-c(2.1,3.2,4.6) typeof(Y) #### NOTE !!!#### x^2 # is not a matrix multiplication but the square of each elements in x x*x x^2 # is also elememt by element multiplication just like x^2, not matrix multiplication
H<-t(x) # %$ performs matrix multiplication H%%x #### B-LISTS #### # vectors must have elements of the same type # unlike vectors , we can have different typeof characters within the list z<-c(1,2,“n”) typeof(z) # since vectors must always have elements of the same type and # ww entered z as a vector, R is forcing every element in Z to be recognized as char # hence 1 is define as char “1” just like “n”.
A<-list(1,2,“n”) str(A) # we can obeserve from the structure of A str(A) that I and 2 are number while n # is a character, proving the list allows different elements in an array.
G<-as.list(z) str(G) G[1] G[2] G[1]<-as.numeric(G[1]) G[1]<-as.numeric(G[1]) #### Conversting a list to vector #### #Conversting a list to vector unsing: unlist() if all elements are the same type B<-unlist(G) typeof(B) # B is a vector of characters as elements.
C<-cbind(x,Y) print(C) D<-rbind(x,Y) print(D) # Squares elements in the matrix C^2 CC # Matrix multiploication: %% C%*%D #### Data Frame #### #### as.data.frame converts matrices to data frames #### F<-as.data.frame(C) print(F) # The $ operator pulls out columns of a data frameby name F\(x # change elements of column X from unm to char F\)x<-as.character(F\(x) #Elements of a data Frame F[1,1] F[2,2] F[3,2] # columns of a data frame F\)x F[,1] # Rows of a data Frame F[1,] # Can call columns by position too F[,2]<-as.character(F[,2]) str(F) print(F) class(F) F^2 # impossible because the elements in F are non numeric F[,1]<-as.numeric(F[,1]) F[,2]<-as.numeric(F[,2]) # Convert Data frame back to matrices F<-as.matrix(F) class(F) # use class() to know if it’s a matrix, data frame, list R<-F^2 print(F) print(R) class(R) R<-as.data.frame(R) #### Making a column as a factor #### # using as.factor R\(x<-as.factor(R\)x) # R recognise elements in column “4”,“9”,“16” as 3 distinct (factor)
#Making that new column as a function of an existing Column of the data frame R\(New<-R\)Y^2 print(R) #### Adding a column of Boolean Variables TRUE / FALSE #### R\(NEW2<-c(TRUE,TRUE,FALSE) # TRUE AND FALSE MUST ALWAYS BE IN CAPITAL R\)New3<-c(“M”,“M”,“F”) print(R) # I want all the M recognised as males and F as Females # I therefore changes M and F from character to Factors R\(New3<-as.factor(R\)New3) print(R) str(R) #### Deleting a column #### R\(new<-NULL R R\)New<-R\(Y^2 R ##### Note NULL is different from NA R\)New<-NA R str(R) # R recognise NA as a logical variable and not zero R\(New<-NULL R R\)NEW<-R$Y^2 R #### DELETTING A COLUMN BY POSITION #### R<-R[,-5] # [,-5] means accross all rows , delete column 5 R