Thursday, January 15, 2015

R Programming 3: Basic Commands and Examples

Assign Values:
x = 11 or x <- 11
print (x) or x and not X as R is case-sensitive.
Ex:-
> x =10
> x
[1] 10
> print(x)
[1] 10
we also can use
x.1 = 14 or x.1 <- 14 bur we can't assign the values like 1.x = 12.
use x.1 or print (x.1) for output.
> x.1 = 10
> x.1
[1] 10
> print(x.1)
[1] 10
> x.2 <- 20
> x.2
[1] 20
> x.1+x.2
[1] 30
> 1.x = 15
Error: unexpected symbol in "1.x"

> A <- matrix(c(1,2,3,4,5,6,7,8),nrow=4,ncol=2)
> A
     [,1] [,2]
[1,]    1    5
[2,]    2    6
[3,]    3    7
[4,]    4    8
> B <- matrix(c(1,2,3,4,5,6,7,8),nrow=4,ncol=2,byrow=TRUE)
> B
     [,1] [,2]
[1,]    1    2
[2,]    3    4
[3,]    5    6
[4,]    7    8
Feeding the data into table:
> pets <- c("cat","bunny","dog")
> weight <-c(5,2,30)
> feed <- c(1,NA,10)
> feed <- c("yes","","no")
> run <- c(1,NA,10)
> house.pets <- data.frame(type=pets,weight,feed,run)
> View(house.pets)
> house.pets
   type weight feed run
1   cat      5  yes   1
2 bunny      2       NA
3   dog     30   no  10

We also can assign Characters to an Object:
xx = "Divakar" or xx = "123" ( here R consider 123 as Characters instead of numbers)
print(xx)

Overwrite Values:
x = 12 or x<- 12
print (x) or x and not X as R is case-sensitive.
 x value will display as 12 as we assigned new value.

Work space Memory:
ls to ask R to know work space memory
ls ()

Remove Work Space memory in R and Object:
rm (x)

Arithmetical Operators:+,-,*,/
5+4
5*5
5/5
6-2
Ex : x = 20 , y= 20 ,
        z<- x+y,
        print(z)

Square:
x square y
Ex :x =2 and y = 4
       x ^2 = 4
       y^2  = 16
> x = 2
> y = 4
> x^2
[1] 4
> y^2
[1] 16
Square root:
sqrt(x)
Ex : x = 25
        sqrt (x) = 5

Log:
log(x)
Ex : x = 2
       log(x) =2.197225

Exponential:
exp(x)

Log basse 2:
log2(x)

Absolute Value:
abs(x)
Ex : x = -14
       abs(x)= 14

Incomplete Commands:
Ex : x = 25
       sqrt(x
       +
       +) = 5

Comments in R:
use # for comments
Ex :
# Sum of x and y
x=20, y=40
z<- x+y or z = x+y
print (z)



To know how to draw plots:
x = 3:5
y = 5:7
plot(x,y,main = "Divakar plot",col.main ="red")















Existing colors:
colours()

Working directory:
getwd()

Graphical Parameters:
par()

## Data Sequences
seq(3,5)
seq(from = 3, to = 5)
seq(from=3,length = 3)
seq(from = 3, length = 3, by = 0.5)

##paste Function - characters
paste ("xyz",1:10)
paste ("xyz",c(2,5,7),"test",4,5))
paste ("xyz",1:10, sep = "")

## to repeat sequences
rep (c(3,4,5),3)
rep (1:10,time =3)
rep (x, each = 3)
rep(x,each = 3,time = 3)

##to asses the position
x = c(4:20)
which(x ==10)

## reverse of
x[3]

# Some Regular Commands:
#attach the data.
attach(input)
length(input)
getwd()
setwd()
rm(list=ls())
install.packages("epiR")
install.packages()
library(epiR)
library(help = "base")


No comments:

Post a Comment