Beruflich Dokumente
Kultur Dokumente
# for comment
x <- 1
print(x)
[1] 1 , here [1] tells that x is a vector and its first element is 1.
1 : 20 prints 1 to 20 nos
Everything in R is a object
List is the only vector which can have object of different class ie integer, characters etc
together
x <- vector(numeric, length = 10) creates a vector with 10 0s(default value of numeric
vector is 0)
MIXING OBJECTS x <- c(1, Apoorv) gives output 1 Apoorv coercion happens so
every element is of same class.
x <- c(1, TRUE) give 1 1
Explicit coercion using as.* fucntion as.logical(x) converts x from say, integer to logical
similarly as.character(x)
Matrix are constructed column wise- m <- matrix( 1:6, nrow =2 , ncol =3)
matrix can also be created from vector using dimension attribute
m <- 1:10
dim(m) <- c(2,5)
matrix can also be created using column or row binding cbin() or rbind()
x<- 1:3
y<- 10:12
cbind(x,y)
FACTORS
used to represent categorical data, ordered and unordered
Think of them to be integer vector with each integer a label.
Use modeling functions lm() and glm()
Factors are self describing so they are better than integers.
X<-factor(c(YES,YES, NO, YES)
output : YES YES NO YES
table(x) , unclass(x)- brings into integer
use levels argument to factor() to set the order of the levels levels = c(YES, NO) doing
this give integer value 1 to NO and 2 to YES
MISSING VALUES- is.na(), is.nan() - tells about missing values, NA values can have
different classes
NA values are not necessarily NAN values
x<- c(1,2, NA, 3,5)
gives : false, false, true, false, false
DATA types- DATA FRAMES
- used to store tabular data, represented as special types of list, every element of list has
same length, each element-column and length of each element- ROW
special attribute- row.names
data frames are created by calling---- read.table() or read.csv()
can be CONVERTED to matrix using data.matrix()
x <- data.frame( foo = 1:4, bar = c(T,F,T,T))
can use nrow(X) to know number of row which is 4 here
NAMES ATTRIBUTE-
we can give name to each element of vector x
x<- 1:3
names(x) <- c(foo, boo, too)
List can also have name x<- list(a=1,b=2,c=3)
x<- runif(100, min=1, max=5) prints 100 nos greater than1 and less than 5
x<- runif(100) prints values between 0 and 1
When two vectors are not of equal length, the shorter one is recycled. For example, The following
adds 0 to all the odd elements and 2 to all the even elements of 1:10:
The head() function extracts the first few rows, and $ operator extracts individual components.