Understanding of Basic R functions

8*6  
## [1] 48
2^5 # 2 to the power 5
## [1] 32
sqrt(16) #square root
## [1] 4
abs(-65) #absolute
## [1] 65

Variables

SquareRoot16 <- sqrt(16)
SquareRoot16
## [1] 4
Hours.Year = 365*24
Hours.Year
## [1] 8760

Vectors & dataframes

Vectors

  • Creating a vector of country names and another vector with avg life expectancies of these 5 countries
Country <- c("Brazil","China","India","Switzerland","USA")
Country
## [1] "Brazil"      "China"       "India"       "Switzerland" "USA"
LifeExpectency <- c(74,76,65,83,79)
LifeExpectency
## [1] 74 76 65 83 79

Should’nt try to combine characters and number in same vector

  • ‘seq’ is used to create a sequence of numbers
  • Sequence starting from 0 upto 100 with increment of 2
seq(0,100,2)
##  [1]   0   2   4   6   8  10  12  14  16  18  20  22  24  26  28  30  32
## [18]  34  36  38  40  42  44  46  48  50  52  54  56  58  60  62  64  66
## [35]  68  70  72  74  76  78  80  82  84  86  88  90  92  94  96  98 100

Dataframes

Now, lets combine our data(vectors) into a dataframe

CountryData <- data.frame(Country,LifeExpectency)
CountryData
##       Country LifeExpectency
## 1      Brazil             74
## 2       China             76
## 3       India             65
## 4 Switzerland             83
## 5         USA             79

Lets add new variable population having population of these coutries to CountryData dataframe

CountryData$Population <- c(199000,1390000,1240000,7997,318000)
CountryData
##       Country LifeExpectency Population
## 1      Brazil             74     199000
## 2       China             76    1390000
## 3       India             65    1240000
## 4 Switzerland             83       7997
## 5         USA             79     318000

Now, let’s say we want to add two new observations for Australia & Greece.

Country <- c("Australia", "Greece")
LifeExpectency <- c (82,81)
Population <- c(23050,11125)
NewCountryData <- data.frame(Country,LifeExpectency,Population)
NewCountryData
##     Country LifeExpectency Population
## 1 Australia             82      23050
## 2    Greece             81      11125

Let’s combine CountryData and NewCountryData

AllCountryData <- rbind(CountryData, NewCountryData)
AllCountryData
##       Country LifeExpectency Population
## 1      Brazil             74     199000
## 2       China             76    1390000
## 3       India             65    1240000
## 4 Switzerland             83       7997
## 5         USA             79     318000
## 6   Australia             82      23050
## 7      Greece             81      11125

List of variables created in current R session

ls()
## [1] "AllCountryData" "Country"        "CountryData"    "Hours.Year"    
## [5] "LifeExpectency" "NewCountryData" "Population"     "SquareRoot16"

Functions Used

abs()
seq() ls()
c()
data.frame()
rbind() - Combines dataframes by stacking the rows