<jupyter_start><jupyter_text>R Basics  Variables   Assignments Using equal sign to assign variable<jupyter_code>x=11
print(x)<jupyter_output>[1] 11<jupyter_text>Using <- to assign variable<jupyter_code>y<-12
print(y)<jupyter_output>[1] 12<jupyter_text>List variable used Use ls command to list all variables<jupyter_code>## ls()<jupyter_output><empty_output><jupyter_text>Use mget with ls to list all variables and values<jupyter_code>## mget(ls())<jupyter_output><empty_output><jupyter_text>Remove variables<jupyter_code>1->z
ls()<jupyter_output><empty_output><jupyter_text>Use rm command to remove the variables<jupyter_code>rm(z)
ls()<jupyter_output><empty_output><jupyter_text>Arithmetic operations<jupyter_code>x+y
x-y
x*y
x/y
x^2
sqrt(y)<jupyter_output><empty_output><jupyter_text>same can be written as using power of half<jupyter_code>y^(1/2)
log(x)
exp(x)
log2(x)
abs(-10)<jupyter_output><empty_output><jupyter_text>Commenting Use  to comment a single line<jupyter_code># comment line<jupyter_output><empty_output><jupyter_text>Data type  logical<jupyter_code>T 
TRUE
class(TRUE)
class(F)<jupyter_output><empty_output><jupyter_text>numeric<jupyter_code>2
class(2)
class(2.5)
class(2L)
is.numeric(2)
is.integer(2)
is.integer(2L)<jupyter_output><empty_output><jupyter_text>Character<jupyter_code>"char"
class("char")<jupyter_output><empty_output><jupyter_text>complex<jupyter_code>3+5i
class(3+5i)<jupyter_output><empty_output><jupyter_text>Raw<jupyter_code>charToRaw("char")
class(charToRaw("char"))<jupyter_output><empty_output><jupyter_text>Coercion<jupyter_code>as.numeric(TRUE)
as.numeric(F)
as.character(4)
as.integer("4.5")
as.numeric("test")<jupyter_output>Warning message in eval(expr, envir, enclos):
"NAs introduced by coercion"<jupyter_text>Vectors  create vector in R Create vector using c command<jupyter_code>toss_coin<-c("H","H","T","H","T","T")
toss_coin
roll_dice<-c(1,6,3,2,4,1,2,5)
roll_dice<jupyter_output><empty_output><jupyter_text>Names for vector Use names function to create names for vector<jupyter_code>coin<-c("Head","Head","Tail","Head","Tail","Tail")
names(toss_coin)<-coin
toss_coin
points<-c("WIN"=2,"LOSS"=0)
points
str(points)<jupyter_output>Named num [1:2] 2 0
 - attr(*, "names")= chr [1:2] "WIN" "LOSS"<jupyter_text>Single value vector R does not provide a data structure to hold a single number or single character string or any other basic data type.They're all just vectors of length 1.<jupyter_code>apple<-5
is.vector(apple)
length(apple)
length(points)<jupyter_output><empty_output><jupyter_text>R vector can only hold elements of the __same type__. They are also often called __atomic vectors__, differentiate them from __lists__, another data structure which can hold elements of __different types__. This means that you cannot have a vector that contains both logical and numerics for example. If you do try to build such a vector, R __automatically performs coercion__ to make sure that you end up with a vector that contains elements of the __same type__<jupyter_code>drawn_ranks<-c("A",3,"Q",10,5,"K")
drawn_ranks
class(drawn_ranks)<jupyter_output><empty_output><jupyter_text>Vector calculus vectors in R is that, they will be applied __elements by elements__. This means that standard mathematics is extended to vectors in __element-wise fashion__<jupyter_code>earnings<-c(50,100,200)
earnings*50
earnings/10
earnings-50
earnings+50
expenses<-c(10,20,30)
earnings-expenses
sum(earnings)
earnings>expenses<jupyter_output><empty_output><jupyter_text>Subsetting Vectors use __square brackets__ for getting values from vector<jupyter_code>earnings[1]
points["WIN"]
coin[c(1,5)]<jupyter_output><empty_output><jupyter_text>__minus__ symbol to get the values from backward<jupyter_code>points[-1]
coin[-c(1,5)]<jupyter_output><empty_output><jupyter_text>Use logical values to filter the value.<jupyter_code>points[c(TRUE,FALSE)]<jupyter_output><empty_output><jupyter_text>If length is less it uses the cyclic pattern to filter<jupyter_code>coin[c(TRUE,FALSE)]
toss_coin['Head']<jupyter_output><empty_output><jupyter_text>HandsOn Create a vector __V1__ with values __1 to 5__. Create another vector __V2__ with values __(10,20,30,40,50)__. __Add__ vectors __V1__ and __V2__ and __print__.<jupyter_code>V1<-c(1,2,3,4,5)
V2<-c(10,20,30,40,50)
print(V1+V2)<jupyter_output>[1] 11 22 33 44 55<jupyter_text>Factor and levels Categorical variables* Limited number of different values* Belong to category* Using factor in R<jupyter_code>blood <- c("B","AB","O","A","O","O","A","B")

blood<jupyter_output><empty_output><jupyter_text>Create factorUse factor command to convert to factor.R sorts levels alphabetical<jupyter_code>blood_factor <- factor(blood)
blood_factor<jupyter_output><empty_output><jupyter_text>Levels are numericaly encoded<jupyter_code>str(blood_factor)<jupyter_output>Factor w/ 4 levels "A","AB","B","O": 3 2 4 1 4 4 1 3<jupyter_text>change the level order<jupyter_code>blood_factor2 <- factor(blood,levels=c("O","A","B","AB"))
blood_factor2
str(blood_factor2)<jupyter_output>Factor w/ 4 levels "O","A","B","AB": 3 4 1 2 1 1 2 3<jupyter_text>Rename the factor level<jupyter_code>levels(blood_factor2) <- c("BT_O","BT_A","BT_B","BT_AB")
blood_factor2
factor(blood,levels=c("O","A","B","AB"),labels=c("BT_O","BT_A","BT_B","BT_AB"))<jupyter_output><empty_output><jupyter_text>Nominal versus Ordinal We cannot compare the each factor values which are not ordered as below:factor[1] < factor[2]<jupyter_code>blood_factor[1] < blood_factor[2]
tshirt<-c("M","L","S","S","L","M","S")
tshirt_facotr<-factor(tshirt,ordered = TRUE,levels=c("S","M","L"))
tshirt_facotr
tshirt[1] < tshirt[2]<jupyter_output><empty_output><jupyter_text>HandsOn Create a variable of type factor with values "yes", "no", "yes", "maybe" and print the levels in this variable.<jupyter_code>a <- factor(c("yes", "no", "yes", "maybe"))
print(levels(a))<jupyter_output>[1] "maybe" "no"    "yes"<jupyter_text>Date and Time in R * Dates are represented by the Date class * Times are represented by the POSIXct and POSIXlt class* Dates are stored internally as number of days since 1970-01-01* Times are stored internally as number of seconds since 1970-01-01<jupyter_code>d<-as.Date("1970-01-01")
print(d)
class(d)<jupyter_output><empty_output><jupyter_text>unclass to get the internal stored values of the date<jupyter_code>unclass(d)
unclass(as.Date("1970-01-02"))<jupyter_output><empty_output><jupyter_text>HandsOn Create a string __"25-12-2016"__ and convert it into date format and print the date.___Hint___: Please specify the format of the string being used as __%d-%m-%Y__<jupyter_code>s<-"25-12-2016"
date<-as.Date(s,format = "%d-%m-%Y")
print(date)<jupyter_output>[1] "2016-12-25"<jupyter_text>Matrix  Create and name Matrix __Vector__ is a __sequence__ of data elements which is __one dimensional__. __Matrix__ is a similar collection of data elements but, this time arranged into a fixed number of __rows__ and __columns__The matrix can contain only one __atomic vector__ type, this means that you can't have logical and numeric matrix.Use matrix command to create matrix<jupyter_code>matrix(1:6,nrow = 2)
matrix(1:6,ncol = 3)<jupyter_output><empty_output><jupyter_text>Suppose you pass the vector containing the values 1 to 3 to the matrix() function and explicitly say you want a matrix with two rows and three columns. R fills up the matrix column by column and simply repeats the vector<jupyter_code>matrix(1:3,nrow = 2,ncol = 3)<jupyter_output><empty_output><jupyter_text>If you try to fill up the matrix with a vector whose multiple does not nicely fit in a matrix, for example, when you want to put the four elements vector in the six element matrix. R generates a warning message<jupyter_code>matrix(1:4,nrow = 2,ncol = 3)<jupyter_output>Warning message in matrix(1:4, nrow = 2, ncol = 3):
"data length [4] is not a sub-multiple or multiple of the number of columns [3]"<jupyter_text>cbind() and rbind()<jupyter_code>cbind(1:3,1:3)
rbind(1:3,1:3)
m<-matrix(1:6,byrow=TRUE,nrow=2)
rbind(m,7:9)
cbind(m,10:11)<jupyter_output><empty_output><jupyter_text>rownames() and colnames()<jupyter_code>rownames(m)<-c("row1","row2")
m
colnames(m)<-c("col1","col2","col3")
m
m1<-matrix(1:6,nrow = 2,ncol = 3,dimnames = list(c("row1","row2"),c("col1","col2","col3")))
m1<jupyter_output><empty_output><jupyter_text>Coercion<jupyter_code>num<-matrix(1:8,ncol = 2)
num
char<-matrix(LETTERS[1:6],nrow = 4,ncol = 3)
char
cbind(num,char)<jupyter_output><empty_output><jupyter_text>Subsetting Matrices you can use square brackets ([]) for this<jupyter_code>m<-matrix(sample(1:15,12),nrow = 3)
m<jupyter_output><empty_output><jupyter_text>Getting value first row and third columns as below<jupyter_code>m[1,3]<jupyter_output><empty_output><jupyter_text>Selecting enitre row or column using square bracket with one value with comma To get  entire first row as below<jupyter_code>m[1,]<jupyter_output><empty_output><jupyter_text>To get entire first column as below<jupyter_code>m[,1]<jupyter_output><empty_output><jupyter_text>Suppose you simply type m[4], result is 9. How did R getting it? Well when you pass a single index to subset a matrix, R simply goes through the matrix column by column from left to right. The first index is 15, the second one 11, the third 14 and the fouth one is 9 in the next column<jupyter_code>m[4]<jupyter_output><empty_output><jupyter_text>Mutiple values with matrix can be done similar to vector subsetting. Second row and column 2 and 3 as below<jupyter_code>m[2,c(2,3)]<jupyter_output><empty_output><jupyter_text>First and second row with column second and third as below<jupyter_code>m[c(1,2),c(2,3)]<jupyter_output><empty_output><jupyter_text>subset by name<jupyter_code>rownames(m)<-c("r1","r2","r3")
colnames(m)<-c("a","b","c","d")
m<jupyter_output><empty_output><jupyter_text>Use names to subset the matrix as below<jupyter_code>m["r1","c"]<jupyter_output><empty_output><jupyter_text>Can use both number and name to subset the matrix as below<jupyter_code>m[2,"c"]<jupyter_output><empty_output><jupyter_text>subset by logical values Get value of row first and second with column four as below using logical values<jupyter_code>m[c(T,T,F),c(F,F,F,T)]<jupyter_output><empty_output><jupyter_text>Matrix Arithmetic We can use rowSums and colSums to sum by row and sum by columns respectively Let take revenue of lord of ring in US dollars as below<jupyter_code>the_fellowship<-c(316,556)
two_towers<-c(343,584)
return_king<-c(378,742)
lotr_matrix<-rbind(the_fellowship,two_towers,return_king)
rownames(lotr_matrix)<-c("Fellowship","Tow towers","Return King")
colnames(lotr_matrix)<-c("US","non-US")
lotr_matrix<jupyter_output><empty_output><jupyter_text>Let convert the value to Euro by dividing 1.12 Matrix with scalar arthmetic<jupyter_code>lotr_matrix/1.12
theater_cut<-rbind(c(50,50),c(80,80),c(100,100))
theater_cut<jupyter_output><empty_output><jupyter_text>Matrix Matrix arthmetic<jupyter_code>lotr_matrix-theater_cut<jupyter_output><empty_output><jupyter_text>Recycling  Same as above result with vector value. This use the recycle values for arthmetic operation<jupyter_code>lotr_matrix-c(50,80,100)<jupyter_output><empty_output><jupyter_text>Matrix Multiplication<jupyter_code>rates<-matrix(c(1.11,0.99,0.82),nrow = 3,ncol =2 )
rates
lotr_matrix*rates<jupyter_output><empty_output><jupyter_text>HandsOn Create a vector __"V"__ with values __1 to 9__. Then, create a __3*3 matrix "M"__ using the vector __V__ and by __row = TRUE__. __Multiply__ all elements in the matrix by __2__ and __print__.<jupyter_code>V<-1:9
M<-matrix(V,nrow = 3,ncol = 3,byrow = TRUE)
M
print(M*2)<jupyter_output>[,1] [,2] [,3]
[1,]    2    4    6
[2,]    8   10   12
[3,]   14   16   18<jupyter_text>Numeric to Categorical Variable in R<jupyter_code>height<-sample(50:100,50)
height<jupyter_output><empty_output><jupyter_text>create category by <50,50-55,55-60,60-65,65-70,70+<jupyter_code>cutheight<-cut(height,breaks = c(0,50,55,60,65,70,100),labels = c("A","B","C","D","E","F"))
cutheight[1:10]<jupyter_output><empty_output><jupyter_text>__right__ attribute is used to have value __TRUE__ or __FALSE__. If __FALSE__ right open interval __[a,b)__ else right closed interval __(a,b]__ __breaks__ attribute may have single value or mutiple value to specify the interval like __breaks =5__ or __breaks = c(0,50,55,60,65,70,100)__  HandsOn Create a factor vector __v1__ using __10 random numbers without decimals__. Then, convert that __factor vector__ to __numeric vector v2__. Check if all values in __v1__ and __v2__ match.<jupyter_code>v1<-factor(sample(1:10,10))
v1
v2<-as.numeric(v1)
v2
print(v1==v2)<jupyter_output>[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE<jupyter_text>Random Numbers in R A __uniform random__ variable is equally likely from __0 to whatever number__ or from __a lower end to a upper end__.__runif()__ this function which stands for random uniform.* first argument is number of random generated values.* second argument is lower number.* third argument is upper number. Random number for 15 numbers and lower is 0 and upper is 10<jupyter_code>runif(15,0,10)<jupyter_output><empty_output><jupyter_text>Create random number of 1000 from 0 to 10 and show histogram<jupyter_code>x1<-runif(1000,0,10)
hist(x1,main = "Uniform")<jupyter_output><empty_output><jupyter_text>__Exponential random variable__ use the __rexp()__* first argument is number of random generated values.* second argument is mean of the distribution the exponential distribution. Create exponential random variable of 500 with 0.2 mean of the distribution<jupyter_code>x2<-rexp(500,0.2)
hist(x2,main="Exponential")<jupyter_output><empty_output><jupyter_text>__Normal distribution__ is done using __rnorm()__ * first argument is number of random generated values.* second argument is mean of the distribution.* third argument is standard deviation of the distribution.<jupyter_code>x3<-rnorm(10000,15,2)
hist(x3,main="Normal")<jupyter_output><empty_output><jupyter_text>A __discrete distribution__ that we might be interested in sampling values from is a __poisson random variable____rpois()__ function with two arguments* first argument is number of random generated values.* second argument is mean of the distribution.<jupyter_code>x4<-rpois(700,10)
hist(x4,main="Poisson")<jupyter_output><empty_output><jupyter_text>Here's my histogram for my poisson random variable. Notice that it still skewed to the right a bit and all of these values that are generated are actually discrete and they are whole numbers. So, they go from 0 to infinity, but they're all the counting number; 0,1,2,3,4,5,6,7,8,9,10 and so on. There are no decimal values appear, even that you can't see that from this histogram __Binomial distribution__ uses function __rbinom()__* first argument is number of random generated values.* second argument is N.* third argument is probability of success.<jupyter_code>x5<-rbinom(300,10,0.3)
hist(x5,main="Binomial")<jupyter_output><empty_output><jupyter_text>HandsOn Create a vector __"V"__ with __10__ random numbers with __2 decimals__. Check if the values of the __vector are less than 0.50__.<jupyter_code>V<-round(runif(10),2)
V
V<0.50<jupyter_output><empty_output><jupyter_text>Random SamplingTwo types of sampling in statistics:* sampling without replacement(which is the default setting with R)* sampling with replacement  Random sample without replacement<jupyter_code>U<-1:10
U
sample(U,5)
sample(U,)
sample(U,11)<jupyter_output><empty_output><jupyter_text>Random sample with replacement<jupyter_code>sample(U,12,replace = TRUE)
V<-4
sample(V,1)<jupyter_output><empty_output><jupyter_text>It actually takes that value there and if there's a single value such as 4, it actually understand that as any value from 1 to 4. So, it actually read states as follows sample(c(1,2,3,4), 1). So, any value from 1 to 4, rather than 4 itself<jupyter_code>sample(c(1,2,3,4), 1)<jupyter_output><empty_output><jupyter_text>Handling Missing Values and Attributes * Testing for missing data that's the first step you should know whether there's any data missing or not. Once we're done that,* We look at how to omit that missing data so that we have our data set complete.* The third part we'll see how we can exclude the missing data instead of omitting it and then perform our computations or analysis. In R missing data is represented by __NA__, that stands for __Not Available__<jupyter_code>print(NA)
class(NA)
a<-c(1,2,3,4,5,1,2,3,4,5)
a[10]<-NA
print(a)<jupyter_output>[1]  1  2  3  4  5  1  2  3  4 NA<jupyter_text>__is.na()__ will test if there is missing data, right<jupyter_code>is.na(a)
a[is.na(a)]
!is.na(a)
a[!is.na(a)]<jupyter_output><empty_output><jupyter_text>Easier way of doing using __omit()__<jupyter_code>na.omit(a)
print(na.omit(a))<jupyter_output>[1] 1 2 3 4 5 1 2 3 4
attr(,"na.action")
[1] 10
attr(,"class")
[1] "omit"<jupyter_text>Additional values can be stored for variables which is call attributes<jupyter_code>attributes(na.omit(a))
attr(na.omit(a),"na.action")
attr(attr(na.omit(a),"na.action"),"class")
at<-10
attributes(at)
attr(at,"attrb")<-"test value"
attributes(at)
rm(at)
a[a==1]
a[!a==1]
a %in% c(1,3)
a[a %in% c(1,3)]<jupyter_output><empty_output><jupyter_text>We can use __%in%__ rather and __==__ as it removes NA Extract even value of a<jupyter_code>b<-a[a%%2==0]
b[!is.na(b)]<jupyter_output><empty_output><jupyter_text>Extract odd value of a<jupyter_code>c<-a[!a%%2==0]
c[!is.na(c)]<jupyter_output><empty_output><jupyter_text>HandsOnCreate a vector __"V"__ with values __(1, 4, NA, 7, 9, NA, 2)__. Remove __NA's__ and __all odd numbers__ from the vector and print the vector __"V"__.<jupyter_code>V<-c(1, 4, NA, 7, 9, NA, 2)
V<-V[!is.na(V)]
V<-V[V%%2==0]
print(V)<jupyter_output>[1] 4 2<jupyter_text>Set Operations in R<jupyter_code>U<-1:9
A<-c(1,4,5,6,7)
B<-c(2,4,6,7,9)<jupyter_output><empty_output><jupyter_text>Now, the two most common commands in set theory will be* union* intersection Look at the union of A and B using __union()__ function<jupyter_code>union(A,B)<jupyter_output><empty_output><jupyter_text>Sorting above union values<jupyter_code>sort(union(A,B))<jupyter_output><empty_output><jupyter_text>Look at the intersection of A and B using intersect() function<jupyter_code>intersect(A,B)<jupyter_output><empty_output><jupyter_text>__Complement__ using set difference __setdiff()__ function Value only in A and not in B<jupyter_code>setdiff(A,B)<jupyter_output><empty_output><jupyter_text>Value only in B and not in A<jupyter_code>setdiff(B,A)<jupyter_output><empty_output><jupyter_text>Value not in A but in universal set U<jupyter_code>setdiff(U,A)<jupyter_output><empty_output><jupyter_text>Value not in B but in universal set U<jupyter_code>setdiff(U,B)<jupyter_output><empty_output><jupyter_text>HandsOn Create a vector __"A"__ with values __11 to 16__. Create another vector __"B"__ with values __13 to 20__. Find the __elements in "A" that are not in "B"__.<jupyter_code>A<-11:16
B<-13:20
setdiff(A,B)<jupyter_output><empty_output><jupyter_text>Descriptive Statistics (Mean, Median, Mode)<jupyter_code>X<-c(13,16,19,20,31,42,55,67,71,82)<jupyter_output><empty_output><jupyter_text>Mean can be found using __mean()__ function<jupyter_code>mean(X)<jupyter_output><empty_output><jupyter_text>Median can be found using __median()__ function<jupyter_code>median(X)
length(X)<jupyter_output><empty_output><jupyter_text>Standard deviation can be found using __sd()__ function<jupyter_code>sd(X)<jupyter_output><empty_output><jupyter_text>Variance can be found using var() function<jupyter_code>var(X)<jupyter_output><empty_output><jupyter_text>HandsOnCreate a vector __"A"__ with values __11 to 17__. Find the __median__ of this vector.<jupyter_code>A<-11:17
median(A)<jupyter_output><empty_output><jupyter_text>Conditional and Loops  Conditional Statements in Rif statement and logical operators examples<jupyter_code>stock<-runif(50,0,50)
stock
if(stock[1] < 25) {
    print("First element is less than mean ")
}else if (stock[1] > 25){
    print("First element is greater than mean ")
}else {
    print("First element is equals to mean")
}
cond<-stock[1]<25
status<-ifelse(cond,"First element is less than mean ","First element is equals to mean")
cond<-stock[1]>25
ifelse(cond,"First element is greater than mean ",status)
table(status)
x<-sample(-1:13,10)
y<-sample(-1:13,10)
x
y
x>0<jupyter_output><empty_output><jupyter_text>Check all the values in vector are greater than zero<jupyter_code>all(x>0)
x==y<jupyter_output><empty_output><jupyter_text>Check any values in vector x are in vector y<jupyter_code>any(x==y)<jupyter_output><empty_output><jupyter_text>Check values in both element in vector greater than 0(pair of values)<jupyter_code>x>0 & y>0<jupyter_output><empty_output><jupyter_text>Check values in either element in vector greater than 0(pair of values)<jupyter_code>x>0 | y>0<jupyter_output><empty_output><jupyter_text>__which()__ - Show all the index that statisfies the condition<jupyter_code>which(x>0)<jupyter_output><empty_output><jupyter_text>HandsOnCreate a vector __"Marks"__ with values __78, 85, 90__. Check if the __marks__ are __greater than or equal to 80__, if yes, print __"Above Average"__. If the marks are __less than 80__, print __"Average"__.<jupyter_code>Marks<-c(78,85,90)
if(Marks[1]>=80){
    print("Above Average")
}else{
    print("Average")
}

if(Marks[2]>=80){
    print("Above Average")
}else{
    print("Average")
}

if(Marks[3]>=80){
    print("Above Average")
}else{
    print("Average")
}


condition<-Marks>=80
status<-ifelse(condition,"Above Average","Average")
print(status)
table(status)<jupyter_output><empty_output><jupyter_text>Create a sequence of numbers from __10 to 20__ and assign it to variable __"M"__ & then identify the position of the values whose values are __greater than 13 & less than 16__.<jupyter_code>M<-10:20
which(M>13 & M<16)<jupyter_output><empty_output><jupyter_text>for() Loops in R A for loop is a structure used to execute a __set of code repeatedly__. The for loop statement specifier is an index over which the loop is computed.<jupyter_code>t<-sample(0:10,10)
t
for(i in 1:10){
    t<-append(t,i^2)
    
}
t<jupyter_output><empty_output><jupyter_text>HandsOn Create a vector __"x"__ with numbers __80 to 100__ and try to find the __sum of all even numbers__ in the Vector using __For loop__. (Note both 80 & 100 is inclusive).<jupyter_code>x<-80:100
x
even<-x[x%%2==0]
even
sum=0
for(i in even){
    sum<-sum+i
}
print(sum)<jupyter_output>[1] 990<jupyter_text>ListsA list contain __all kinds of objects__, such as vectors and matrices, but also other R objects such as dates, data frames, factors and many more<jupyter_code>c("text",10,3.5)
print(list("text",10,3.5))
d<-list("text",10,3.5)
d
names(d)<-c("titile","duration","rating")
print(d)
d<-list(title="text",duration=10,rating=3.5)
print(d)
str(d)<jupyter_output>List of 3
 $ title   : chr "text"
 $ duration: num 10
 $ rating  : num 3.5<jupyter_text>List in List<jupyter_code>e<-list(title="text new",duration=5,rating=4)
print(e)
d<-list(title="text",duration=10,rating=3.5,similar=e)
str(d)<jupyter_output>List of 4
 $ title   : chr "text"
 $ duration: num 10
 $ rating  : num 3.5
 $ similar :List of 3
  ..$ title   : chr "text new"
  ..$ duration: num 5
  ..$ rating  : num 4<jupyter_text>R Functions  Writing Functions<jupyter_code>set.seed(100)
d<-rpois(25,8)
d<jupyter_output><empty_output><jupyter_text>Function without return value<jupyter_code>GetMeanAndSE<-function(x){
    m<-mean(x)
    l<-length(x)
    SE<-sd(x)/sqrt(l)
}
GetMeanAndSE(d)<jupyter_output><empty_output><jupyter_text>Function with return value<jupyter_code>GetMeanAndSE<-function(x){
    m<-mean(x)
    l<-length(x)
    SE<-sd(x)/sqrt(l)
    return(c(m,SE))
}
GetMeanAndSE(d)<jupyter_output><empty_output><jupyter_text>HandsOnCreate a function by name __Cube()__ which generates __cube of any given number__. Find the __cube of 10__ and print.<jupyter_code>Cube<-function(x){
    return(x^3)
}
Cube(10)<jupyter_output><empty_output><jupyter_text>Additional HandsOn Create a variable __"L"__ and assign the value of __current year(2016)__ to it. Create another variable __"NL"__ and assign value of __Next leap year__ using variable __"L"__ and __print "NL"__.<jupyter_code>L<-2016
NL<-L+4
print(NL)<jupyter_output>[1] 2020<jupyter_text>Create a variable __"L"__ and assign a value __100__. Create another variable __"LL"__ and assign a value __2__. Find __Square root of L__ and __multiply__ it with __LL__.<jupyter_code>L<-100
LL<-2
print(sqrt(L)*LL)<jupyter_output>[1] 20<jupyter_text>Create a variable __"K"__ and assign a value __2.7__ to it. Check the __data type__ of the variable __K__. If it is __not "integer"__ convert it into __Integer__ and __print the value__?<jupyter_code>K<-2.7
if(class(K)!="integer"){
    print(as.integer(K))
}<jupyter_output>[1] 2<jupyter_text>Create a factor __"color"__ of __3 colors (Red/Green/Blue)__. Find the __number of levels__.<jupyter_code>color<-factor(c("Red","Green","Blue"))
length(levels(color))<jupyter_output><empty_output><jupyter_text>Create a __sequence of even numbers__ between __1 to 10__, __repeating twice__.<jupyter_code>s<-rep(seq(2,10,by=2),2)
print(s)
s<-s[s%%==0]<jupyter_output><empty_output><jupyter_text>Create vector __X__ with values __1 to 5__ and another vector __Y__ with values __(2,4,6,8,10)__. __Multiply Vector X__ with __Vector Y__ and __Print__ the results<jupyter_code>X<-1:5
Y<-c(2,4,6,8,10)
print(X*Y)<jupyter_output>[1]  2  8 18 32 50<jupyter_text>Create a __2 X 3__ matrix __MM__ with elements __(2,4,6,8,0,9)__<jupyter_code>MM=matrix(c(2,4,6,8,0,9),nrow = 2,ncol = 3,byrow = T)
print(MM)<jupyter_output>[,1] [,2] [,3]
[1,]    2    4    6
[2,]    8    0    9<jupyter_text>Create a string __"15081947"__ and convert it into __valid date__.<jupyter_code>S<-"15081947"
d<-as.Date(S,format = "%d%m%Y")
print(d)<jupyter_output>[1] "1947-08-15"<jupyter_text>Create a __variable__ of value __(15 Aug 1947) and (15 Aug 2016)__ in __Posix Date format__ and try to find the __number of days elapsed since Independence as of 15th August 2016__?<jupyter_code>d1<-as.Date("1947-08-15")
d2<-as.Date("2016-08-15")
print(d2-d1)<jupyter_output>Time difference of 25203 days<jupyter_text>Create a vector __temp__ with values __(103,100,98)__. Create a conditional clause mentioning, if __temperature__ is __greater than 100__ - __"hot"__ else __"good"__<jupyter_code>temp<-c(103,100,98)
cond<-temp>100
status<-ifelse(cond,"hot","good")
print(status)<jupyter_output>[1] "hot"  "good" "good"<jupyter_text>Create a vector __"toppers"__ of __10 random numbers between 80 to 100__. Build a condition to check __If all have crossed more than 90__. If yes, print __"best class"__, else __"needs improvement"__<jupyter_code>toppers<-sample(80:100,10)
toppers
if(all(toppers>90)){
print("best class")
}else{
print("needs improvement")
}<jupyter_output>[1] "needs improvement"<jupyter_text>Write a function __"Nfact"__ to find __n__ __factorial__ using __while loop__ and __print the factorial__. Use this function to find __factorial of 6__<jupyter_code>Nfact<-function(x){
    i<-1
    fact<-1
    while(i<=x){
        fact<-fact*i
        i<-i+1
    }
    return(fact)
}
print(Nfact(6))<jupyter_output>[1] 720<jupyter_text>Find the __sum of the first 20 whole numbers__ and __print__ the total.<jupyter_code>sum<-0
for(i in 1:20){
    sum<-sum+i
}
print(sum)<jupyter_output>[1] 210<jupyter_text>Virat scored __98,102,120,145,175,169,118,177, 101,200__ runs in recent __10__ test matches. Using __Which__ Operator, find the matches where he __scored even number of runs__ and print the match numbers.<jupyter_code>virat<-c(98,102,120,145,175,169,118,177, 101,200)
print(which(virat%%2==0))<jupyter_output>[1]  1  2  3  7 10<jupyter_text>Create a list __"emp"__ with details of an employee - __empno 11, name "Alex", age 32, and dept "sales"__. Inspect the employee details using __str__ function.<jupyter_code>emp<-list(empno=11,name="Alex",age=32,dept="sales")
str(emp)<jupyter_output>List of 4
 $ empno: num 11
 $ name : chr "Alex"
 $ age  : num 32
 $ dept : chr "sales"<jupyter_text>Create a function __"pyth"__ that takes a list of __two values__ and finds the value of the __third parameter__ in __Pythagoras theorem__. Print the value returned by __"pyth"__ for input values __3__ and __4__<jupyter_code>pyth<-function(x,y){
    return(sqrt((x^2)+(y^2)))
}
pyth(3,4)
x <- c("a", "b", "c", "c", "d", "a") 
x[c(1, 3, 4)]
x <- 0:4 
as.logical(x)
x <- 4 
class(x)
x <- c("x", "y", "z") 
as.logical(x)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12460264784993189, 'fraction_numerical': 0.04128969154993538, 'mean_word_length': 7.405167351732238, 'pattern_counts': {'":': 2, '<': 611, '<?xml version=': 0, '>': 488, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '125', 'dir': 'jupyter-structured-clean-dedup', 'id': '573172', 'license': 'MIT', 'n_tokens_mistral': 11417, 'n_tokens_neox': 10483, 'n_words': 2722, 'path': 'R_Basics.ipynb', 'repo_name': 'prawin20/jupyter-python', 'size': '28627'}