Showing posts with label split. Show all posts
Showing posts with label split. Show all posts

Functions used in R

R has a huge list of functions. Below are very commonly used functions which are used in day to day life while working in R.
We will use following object to test the functionality of functions.
 m<-matrix(1:12,6,2)
 a<-array(1:8,c(2,2,2))
 d<-data.frame("Amy",1001,c(78,45,89,78,67))

##1. dim function 

It is used to check the dimensions of an object like matrix, array or data frame. Dim function is not applicable on vectors.

dim(m)
[1] 6 2

dim(a)
[1] 2 2 2

dim(d)
[1] 5 3

##2. head(obj,n) function 

It is used to print the first n lines of an object like matrix or array or data frame. By default n is 5. So we write head(m), it will show first five lines of matrix.
head(m, 2)
        [,1] [,2]
[1,]    1    7
[2,]    2    8

##3.tail (obj,n) function 

It is used to print the last n lines of an object like matrix or array or data frame. By default n is 5. So we write tail(m), it will show last five lines of matrix.
tail(m,2)
[,1] [,2]
[5,]    5   11
[6,]    6   1
2

##4. Str(Object) 

It is used to check the structure of any new object. Like for m it has returned that m is an integer matrix with 6 rows and 2 column. Apart from this it also display the data stored in structure.
str(m)
int [1:6, 1:2] 1 2 3 4 5 6 7 8 9 10 ...

##5 sort(object, decreasing=FALSE/TRUE) 

Sort object is to sort the data of an object in ascending or descending order.
v<-c(9,1, 3, -4,0,-9)
sort(v)
[1] -9 -4  0  1  3  9

##6 order(object,decreasing=FALSE)

order object returns the index number of the object in ascending or descending order 
order(c(4,2,7,1,3,9,10,16,13))
[1] 4 2 5 1 3 6 7 9 8

##7 split(x,f) 

##split function divides the data into groups as defined by f.
data(energy)
expand stature
9.21  Obese
7.53  lean
7.48  lean
8.08  lean
8.09  lean
10.15  Obese

split(energy$expand, energy$stature)
 $lean
7.53 7.48.....
$obese
9.2110.15....

 ## 8) unique(object). 

##Unique function returns the unique value inside a object unique(c(1,1,1,2,2,3,3,3,4,4,4))
[1] 1 2 3

## 9) paste(vector1, vector2, sep= , collapse=). 

Paste concatenates the two vectors according to their index number. First element of vector1 gets concatenated with first element of vector2 and value passed in sep will be placed between them. Now all these elements are collapsed togaeher with value of collapse placed between them The output of paste function is a one element vector which has all elements concatenated together.
part1<-c("M","na","i", "Te")
part2<-c("y","me","s","st")
paste(part1,part2,sep="" ,collapse=" ")

[1] "My name is Test"
paste(part1,part2,sep="." ,collapse="-")
[1] "M.y-na.me-i.s-Te.st"

part1<-c(1,3,5,7)
part2<-c(2,4,6,8)
paste(part1,part2,sep="" ,collapse="")
[1] "12345678"



Translate

Monte Carlo Simulation with R

Stochastic Modeling A stochastic model is a tool for modeling data where uncertainty is present with the input. When input has cert...