Professional Documents
Culture Documents
ClASS-1
The R environment
R is an integrated suite of software facilities for data manipulation, calculation and
graphical display. Among other things it has
an effective data handling and storage facility,
a suite of operators for calculations on arrays, in particular matrices,
a large, coherent, integrated collection of intermediate tools for data analysis,
graphical facilities for data analysis and display either directly at the computer
or on hardcopy, and
a well developed, simple and effective programming language (called ‘S’)
which includes conditionals, loops, user defined recursive functions and input
and output facilities. (Indeed most of the system supplied functions are
themselves written in the S language.)
The term “environment” is intended to characterize it as a fully planned and coherent
system, rather than an incremental accretion of very specific and inflexible tools, as is
frequently the case with other data analysis software.
R commands, case sensitivity, etc.
Technically R is an expression language with a very simple syntax. It is case
sensitive as are most UNIX based packages, so A and a are different symbols and would
refer to different variables. Normally all alphanumeric symbols are allowed (and in
some countries this includes accented letters) plus ‘.’ and ‘_’, with the restriction that a
name must start with ‘.’ or a letter, and if it starts with ‘.’ the second character must
not be a digit. Names are effectively unlimited in length.
Elementary commands consist of either expressions or assignments. If an expression is
given as a command, it is evaluated, printed (unless specifically made invisible), and
the value is lost. An assignment also evaluates an expression and passes the value to a
variable but the result is not automatically printed.
Commands are separated either by a semi-colon (‘;’), or by a newline. Elementary
commands can be grouped together into one compound expression by braces (‘{’ and
‘}’). Comments can be put almost anywhere, starting with a hashmark (‘#’), everything
to the end of the line is a comment.
If a command is not complete at the end of a line, R will give a different prompt, by
default + on second and subsequent lines and continue to read input until the command
is syntactically complete. This prompt may be changed by the user.
Use it as simple calculator
aa=45%%2 (remainder after division)
> aa
[1] 1
> aa1=45%/%2 (the integer part of a fraction)
> aa1
[1] 22
Vectors and assignment
R operates on named data structures. The simplest such structure is the numeric vector,
which is a single entity consisting of an ordered collection of numbers. To set up a
vector named x, say, consisting of five numbers, namely 10.4, 5.6, 3.1, 6.4 and 21.7,
use the R command
> x <- c(10.4, 5.6, 3.1, 6.4, 21.7)
This is an assignment statement using the function c() which in this context can take an
arbitrary number of vector arguments and whose value is a vector got by concatenating
its arguments end to end.7
A number occurring by itself in an expression is taken as a vector of length one.
Notice that the assignment operator (‘<-’), which consists of the two characters ‘<’ (“less
than”) and ‘-’ (“minus”) occurring strictly side-by-side and it ‘points’ to the object
receiving the value of the expression. In most contexts the ‘=’ operator can be used as
an alternative.
Assignment can also be made using the function assign(). An equivalent way of making
the same assignment as above is with:
> assign("x", c(10.4, 5.6, 3.1, 6.4, 21.7))
The usual operator, <-, can be thought of as a syntactic short-cut to this.
Assignments can also be made in the other direction, using the obvious change in the
assignment operator. So the same assignment could be made using
> c(10.4, 5.6, 3.1, 6.4, 21.7) -> x
If an expression is used as a complete command, the value is printed and lost8. So now
if we were to use the command
> 1/x
the reciprocals of the five values would be printed at the terminal (and the value of x, of
course, unchanged).
The further assignment
> y <- c(x, 0, x)
would create a vector y with 11 entries consisting of two copies of x with a zero in the
middle place.
Negative indices can be used to avoid certain elements.
We can select all but second and fifth elements of x.
x=1:40
> y=x[-c(2,5)]
> y
[1] 1 3 4 6 7 8 9 10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29 30 31 32 33
[32] 34 35 36 37 38 39 40
The third through 5th elements of x can be avoided.
z=x[-(3:5)]
> z
[1] 1 2 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30 31 32 33 34
[32] 35 36 37 38 39 40
Vectors can be combined via the function c. For examples, the following two vecto
rs n and s are combined into a new vector containing elements from both vectors.
n = c(2, 3, 5)
> s = c("aa", "bb", "cc", "dd", "ee")
> xx2=c(TRUE,5,8)
> xx2
[1] 1 5 8
CLASS-2
Character vectors
Scalars and vectors can be made up of strings of chara
cters. All elements of a vector must be of the same typ
e.
There are two basic operations we want to perform on character ve
ctor.
Substr()-> it takes arguments substr(x,start,stop),where x is a v
ector of character strings, and start and stop say which characte
rs to keep.e.g , to print the first two letters of each col use.
cols=c("red","blank","blue","white","green")
> substr(cols,1,2)
[1] "re" "bl" "bl" "wh" "gr"
> paste(cols,"flowers",sep="")
[1] "redflowers" "blankflowers" "blueflowers" "whiteflowers"
"greenflowers"
> paste("beautiful",cols,"flowers",sep="")
[1]
"beautifulredflowers" "beautifulblankflowers" "beautifulbluefl
owers"
[4] "beautifulwhiteflowers" "beautifulgreenflowers"
>
paste("beautiful",cols,"flowers")
[1] "beautiful red flowers" "beautiful blank flowers" "beautif
ul blue flowers"
[4] "beautiful white flowers" "beautiful green flowers"
> paste("beautiful",cols,"flowers",collapse = ",")
[1] "beautiful red flowers,beautiful blank flowers,beautiful blu
e flowers,beautiful white flowers,beautiful green flowers"
> uL=ll[]+10
> uL
[1] 10 20 30 40 50 60 70 80 90
>factor(cols)
[1] red blank blue white green
Levels: blank blue green red white
> as.integer(cols)
[1] NA NA NA NA NA
> g1=factor(cols)
> as.integer(g1)
[1] 4 1 2 5 3
levels(g1)
[1] "blank" "blue" "green" "red" "white"
>
> levels(g1)
[1] "blank" "blue" "green" "red" "white"
>
> levels(g1)[1]="black"
> g1
[1] red black blue white green
Levels: black blue green red white
The levels()function can be used to change factor labels as well
.
f1=factor(rep(c("g1","g2"),c(10,12)))
> f1
[1] g1 g1 g1 g1 g1 g1 g1 g1 g1 g1 g2 g2 g2 g2 g2 g2 g2 g2 g2 g2 g2 g2
Levels: g1 g2
> f2=as.integer(f1)
> f2
[1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2
a1=rep(c(0,1),c(3,4))
a2=rep(a1,2)
> a2
[1] 0 0 0 1 1 1 1 0 0 0 1 1 1 1
> a3=factor(a2)
> a3
[1] 0 0 0 1 1 1 1 0 0 0 1 1 1 1
Levels: 0 1
> levels(a3)=c("Male","Female")
> a3
[1] Male Male Male Female Female Female Female Male Male Male Fe
male
[12] Female Female Female
Levels: Male Female
Read data from screen if let the file name "", or just without any parameter:
Large data can be scanned in by just copy and paste, for example paste from EXCEL.
> x <- scan()
Then use "ctrl+v" to paste the data, the data type will be automatically determined.
Vector arithmetic
Vectors can be used in arithmetic expressions, in which case the operations are
performed element by element. Vectors occurring in the same expression need not all
be of the same length. If they are not, the value of the expression is a vector with the
same length as the longest vector which occurs in the expression. Shorter vectors in
the expression are recycled as often as need be (perhaps fractionally) until they match
the length of the longest vector. In particular a constant is simply repeated. So with
the above assignments the command
> v <- 2*x + y + 1
generates a new vector v of length 11 constructed by adding together, element by
element, 2*x repeated 2.2 times, y repeated just once, and 1 repeated 11 times.
The elementary arithmetic operators are the usual +, -, *, / and ^ for raising to a
power. In addition all of the common arithmetic functions are
available. log, exp, sin, cos, tan, sqrt, and so on, all have their usual meaning.
max and min select the largest and smallest elements of a vector respectively.
range is a function whose value is a vector of length two,
namely c(min(x), max(x)).
length(x) is the number of elements in x,
sum(x) gives the total of the elements in x, and
prod(x) their product.
Two statistical functions are mean(x) which calculates the sample mean,
which is the same as sum(x)/length(x), and
var(x) which gives
sum((x-mean(x))^2)/(length(x)-1)
or sample variance. If the argument to var() is an n-by-p matrix the value is a p-by-p sample covariance
matrix got by regarding the rows as independent p-variate sample vectors.
sort(x) returns a vector of the same size as x with the elements arranged in increasing order; however there
are other more flexible sorting facilities available
Note that max and min select the largest and smallest values in their arguments, even if they are given
several vectors. The parallel maximum and minimum functions pmax and pmin return a vector (of length
equal to their longest argument) that contains in each element the largest (smallest) element in that position
in any of the input vectors.
For most purposes the user will not be concerned if the “numbers” in a numeric vector
are integers, reals or even complex. Internally calculations are done as double
precision real numbers, or double precision complex numbers if the input data are
complex.
cc1<- c(5,8,9,10,25)
> cc2<- c(7,8,9,12)
length(cc1)=length(cc2);cc1
[1] 5 8 9 10
Generating regular sequences
R has a number of facilities for generating commonly used sequences of numbers. For
example 1:30 is the vector c(1, 2, …, 29, 30). The colon operator has high priority
within an expression, so, for example 2*1:15 is the vector c(2, 4, …, 28, 30). Put n
<- 10 and compare the sequences 1:n-1 and 1:(n-1).
s5<- rep(seq(4,24,4),2);s5
[1] 4 8 12 16 20 24 4 8 12 16 20 24
> x=c(2,3,4)
> y=c(x,6,7,8)
>
>
> x5=rep(c(4,5),c(5,5))
> x5
[1] 4 4 4 4 4 5 5 5 5 5
> x5=rep(c(4,5),each=5)
> x5
[1] 4 4 4 4 4 5 5 5 5 5
> length(y)
[1] 6
> v1=1:11
> v2=seq(1,60,5)
> v2
[1] 1 6 11 16 21 26 31 36 41 46 51 56
> length(v2)
[1] 12
> v1=c(v1,12)
>
> fre=c(5,15,25,40,28,13,3)
For example 1:30 is the vector c(1, 2, …, 29, 30) . ... That is seq(2,10) is the same vector as 2:10 . Argum
ents to seq()
> ch=rep(c(marks),fre)
> marks=c(1,2,3,4,5,6,7)
> ch=rep(c(marks),fre)
>
> z=c(1,4,5,NA,8,9,NA)
>z
[1] 1 4 5 NA 8 9 NA
> is.na(z)
[1] FALSE FALSE FALSE TRUE FALSE FALSE TRUE
2. Basic Data Types
We look at some of the ways that R can store and organize data. This is a basic
introduction to a small subset of the different data types recognized by R and is not
comprehensive in any sense. The main goal is to demonstrate the different kinds of
information R can handle. It is assumed that you know how to enter data or read data
files which is covered in the first chapter.
Variable Types
2.1.1. Numbers
The way to work with real numbers has already been covered in the first chapter and is
briefly discussed here. The most basic way to store a number is to make an assignment
of a single number:
> a <- 3
>
The “<-” tells R to take the number to the right of the symbol and store it in a variable
whose name is given on the left. You can also use the “=” symbol. When you make an
assignment R does not print out any information. If you want to see what value a
variable has just type the name of the variable on a line and press the enter key:
> a
[1] 3
This allows you to do all sorts of basic operations and save the numbers:
> ls()
[1] "a" "b"
You are not limited to just saving a single number. You can create a list (also called a
“vector”) using the c command:
Examples of the sort of operations you can do on vectors is given in a next chapter.
To initialize a list of numbers the numeric command can be used. For example, to
create a list of 10 numbers, initialized to zero, use the following command:
> typeof(a)
[1] "double"
2.1.2. Strings
You are not limited to just storing numbers. You can also store strings. A string is
specified by using quotes. Both single and double quotes will work:
> typeof(a)
[1] "character"
> a = character(20)
> a
[1] "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""
2.1.3. Factors
Another important way R can store data is as a factor. Often times an experiment
includes trials for different levels of some explanatory variable. For example, when
looking at the impact of carbon dioxide on the growth rate of a tree you might try to
observe how different trees grow when exposed to different preset concentrations of
carbon dioxide. The different levels are also called factors.
Assuming you know how to read in a file, we will look at the data file given in the first
chapter. Several of the variables in the file are factors:
> summary(tree$CHBR)
A1 A2 A3 A4 A5 A6 A7 B1 B2 B3 B4 B5 B6 B7 C1 C2 C3 C4 C5 C6
3 1 1 3 1 3 1 1 3 3 3 3 3 3 1 3 1 3 1 1
C7 CL6 CL7 D1 D2 D3 D4 D5 D6 D7
1 1 1 1 1 3 1 1 1 1
Because the set of options given in the data file corresponding to the “CHBR” column
are not all numbers R automatically assumes that it is a factor. When you use summary
on a factor it does not print out the five point summary, rather it prints out the possible
values and the frequency that they occur.
In this data set several of the columns are factors, but the researchers used numbers to
indicate the different levels. For example, the first column, labeled “C,” is a factor. Each
trees was grown in an environment with one of four different possible levels of carbon
dioxide. The researchers quite sensibly labeled these four environments as 1, 2, 3, and
4. Unfortunately, R cannot determine that these are factors and must assume that they
are regular numbers.
This is a common problem and there is a way to tell R to treat the “C” column as a set of
factors. You specify that a variable is a factor using the factor command. In the following
example we convert tree$C into a factor:
> tree$C
[1] 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3
[39] 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 4
> summary(tree$C)
Min. 1st Qu. Median Mean 3rd Qu. Max.
1.000 2.000 2.000 2.519 3.000 4.000
> tree$C <- factor(tree$C)
> tree$C
[1] 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3
[39] 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 4
Levels: 1 2 3 4
> summary(tree$C)
1 2 3 4
8 23 10 13
> levels(tree$C)
[1] "1" "2" "3" "4"
Once a vector is converted into a set of factors then R treats it differently. A set of
factors have a discrete set of possible values, and it does not make sense to try to find
averages or other numerical descriptions. One thing that is important is the number of
times that each factor appears, called their “frequencies,” which is printed using the
summary command.
> a = c(TRUE,FALSE)
> b = c(FALSE,FALSE)
> a|b
[1] TRUE FALSE
> a||b
[1] TRUE
> xor(a,b)
[1] TRUE FALSE
There are a large number of functions that test to determine the type of a variable. For
example the is.numeric function can determine if a variable is numeric:
> a = c(1,2,3)
> is.numeric(a)
[1] TRUE
> is.factor(a)
[1] FALSE
2.1.4. Data Frames
A data frame is a table or a two-dimensional array-like structure in which
each column contains values of one variable and each row contains one set
of values from each column. It allows to store data in over viewable
rectangular grids corresponds to measurements or values of a instance,
While each col is a vector containing data for a specific variable. Following
are the characteristics of a data frame.
The data stored in a data frame can be of numeric, factor or character type.
>
b1=1:5
> b2=c(12.5,23,19,34,16)
> b3=c("a","b","c","d","e")
> b4=as.Date(c("2014-01-18","2005-06-12","2007-09-27","2006-10-0
9","2011-05-21")
> d1=data.frame(b1,b2,b3,b4);d1
b1 b2 b3 b4
1 1 12.5 a 0001-01-20
2 2 23.0 b 0005-06-20
3 3 19.0 c 0007-09-20
4 4 34.0 d 0006-10-20
5 5 16.0 e 0018-05-20
[1] Use dim() to obtain the dimensions of the data frame (number of rows and number of columns). The
output is a vector.
dim(d1)
5 4
Use nrow() and ncol() to get the number of rows and number of columns, respectively. You can
get the same information by extracting the first and second element of the output vector from
dim().
> nrow(d1)
# same as dim(d1)[1]
[1] 5
> ncol(d1)
# same as dim(d1)[2]
[1] 4
Use head() to obtain the first n observations and tail() to obtain the last n observations; by default,
n = 6. These are good commands for obtaining an intuitive idea of what the data look like without
revealing the entire data set, which could have millions of rows and thousands of columns.
> head(d1)
b1 b2 b3 b4
1 1 12.5 a 0001-01-20
2 2 23.0 b 0005-06-20
3 3 19.0 c 0007-09-20
4 4 34.0 d 0006-10-20
5 5 16.0 e 0018-05-20
> class(d1)
[1] "data.frame"
The str() function returns many useful pieces of information, including the above useful outputs
and the types of data for each column. In this example, “int” denotes that the variable “b1” and
“b2” is numeric (continuous), and “Factor” denotes that the variable “b3” is categorical with 5
categories or levels.
When applied to a data frame, the summary() function is essentially applied to each column, and
the results for all columns are shown together. For a continuous (numeric) variable like “count”,
it returns the 5-number summary. If there are any missing values (denoted by “NA” for a
particular datum), it would also provide a count for them. In this example, there are no missing
values for “count”, so there is no display for the number of NA’s. For a categorical variable like
“b3”, it returns the levels and the number of data in each level.
>
summary(d1)
b1 b2 b3
Min. :1 Min. :12.5 a:1
1st Qu.:2 1st Qu.:16.0 b:1
Median :3 Median :19.0 c:1
Mean :3 Mean :20.9 d:1
3rd Qu.:4 3rd Qu.:23.0 e:1
Max. :5 Max. :34.0
Another way that information is stored is in data frames. This is a way to take many
vectors of different types and store them in the same variable. The vectors can be of all
different types. For example, a data frame may contain many lists, and each list might
be a list of factors, strings, or numbers.
There are different ways to create and manipulate data frames. Most are beyond the
scope of this introduction. They are only mentioned here to offer a more complete
description. Please see the first chapter for more information on data frames.
The subset function is available in base R and can be used to return subsets of a vector, martix, or data frame
which meet a particular condition. In my three years of using R, examples of the subset function.
Matrices in R
Matrices are Data frames which contain lists of homogeneous data in a tabular
format. We can perform arithmetic operations on some elements of the matrix
or the whole matrix itself in R.
Let us see how to convert a single dimension vector into a two-dimensional
array using the matrix() function:
v1_1<-seq(1,100)
> m1_1=matrix(v1_1,nrow = 10)
> m1_1
Matrices can represent the binding of two or more vectors of equal length. If
we have the X and Y coordinates for five quadrats within a grid, we can
use cbind()(combine by columns) or rbind() (combine by rows) functions to
combine them into a single matrix, as follows:
sample() function
sample() function is a randomly determined number, if you try this function repeatedly, you’ll ge
t different results every time. This is the correct behavior in most cases, but sometimes you may
want to get repeatable results every time you run the function.
sample(numvec,5,replace=FALSE)
[1] 11 9 6 7 8
One can use sample() to take samples from the data frame (data frame-df_n). In this case, you m
ay want to use the argument replace=FALSE. Because this is the default value of the replace arg
ument, you don’t need to write it explicitly:
Tables
Another common way to store information is in a table. Here we look at how to define
both one way and two way tables. We only look at how to create and define tables; the
functions used in the analysis of proportions are examined in another chapter.
$dimnames
$dimnames$a
[1] "A" "B" "C"
$class
[1] "table"
> summary(results)
Number of cases in table: 9
Number of factors: 1
If you know the number of occurrences for each factor then it is possible to create the
table directly, but the process is, unfortunately, a bit more convoluted. There is an
easier way to define one-way tables (a table with one row), but it does not extend easily
to two-way tables (tables with more than one row). You must first create a matrix of
numbers. A matrix is like a vector in that it is a list of numbers, but it is different in that
you can have both rows and columns of numbers. For example, in our example above
the number of occurrences of “A” is 4, the number of occurrences of “B” is 3, and the
number of occurrences of “C” is 2. We will create one row of numbers. The first column
contains a 4, the second column contains a 3, and the third column contains a 2:
> occur <- matrix(c(4,3,2),ncol=3,byrow=TRUE)
> occur
[,1] [,2] [,3]
[1,] 4 3 2
At this point the variable “occur” is a matrix with one row and three columns of numbers.
To dress it up and use it as a table we would like to give it labels for each columns just
like in the previous example. Once that is done we convert the matrix to a table using
the as.table command:
$dimnames
$dimnames[[1]]
[1] "A"
$dimnames[[2]]
[1] "A" "B" "C"
$class
[1] "table"
Just as in the case with one-way tables it is possible to manually enter two way tables.
The procedure is exactly the same as above except that we now have more than one
row. We give a brief example below to demonstrate how to enter a two-way table that
includes breakdown of a group of people by both their gender and whether or not they
smoke. You enter all of the data as one long list but tell R to break it up into some
number of columns:
> sexsmoke<-matrix(c(70,120,65,140),ncol=2,byrow=TRUE)
> rownames(sexsmoke)<-c("male","female")
> colnames(sexsmoke)<-c("smoke","nosmoke")
> sexsmoke <- as.table(sexsmoke)
> sexsmoke
smoke nosmoke
male 70 120
female 65 140
> x1=c(6,9,8)
> x2=c(12,11,15,18)
> x3=c(14,11,15,18,12,10)
> x4=c(12,8,11,9,10)
> z1=list(x,y,x1,x2,x3,x4)
> lapply(z1,mean)
[[1]]
[1] 12.6
[[2]]
[1] 12
[[3]]
[1] 7.666667
[[4]]
[1] 14
[[5]]
[1] 13.33333
[[6]]
[1] 10
> sapply(z1,mean)
[1] 12.600000 12.000000 7.666667 14.000000 13.333333 10.000000
for (i in 0:7){
+ den_bin=(factorial(n)/(factorial(i)*factorial(n-i)))*(prob_succ^i)*(prob_fail^(n-
i))
+ den_bin
+ print(den_bin)}
statement
mf1<-function(x,y){
+ p1<- x^y
+ p2<-x^2+x^y+y^2+y*exp(x)
+ p3<-seq(x,y)
+ p4<-sample(y,x)
+ print(p1);print(p2);print(p3);print(p4)}
> mf1(2,10)
[1] 1024
[1] 1201.891
[1] 2 3 4 5 6 7 8 9 10
[1] 10 4
Example
v1_1<-seq(1,100)
mf1<-function(x){
m1=mean(x)
md=median(x)
m3=sum(x)
print(m1);print(md);print(m3)}
mf1(v1_1)
R if statement
IFELSE statement
res=c(30,48,59,68,18,59)
> ifelse(res<=40,"FAIL","PASS")
[1] "FAIL" "PASS" "PASS" "PASS" "FAIL" "PASS"
if (test_expression) {
statement
Flowchart of if statement
Example: if statement
x <- 5 ;x1<-20
> if(x < x1){
+ print(x1)
+ }
[1] 20
if…else statement
The syntax of if…else statement is:
if (test_expression) {
statement1
} else {
statement2
}
The else part is optional and is only evaluated
if test_expression is FALSE.
It is important to note that else must be in the same line as the closing
braces of the if statement.
if (x > x1) {
+ print(x)
+ } else {
+ print(x1)
+ }
[1] 20
if…else Ladder
The if…else ladder (if…else…if) statement allows you execute a block of
code among more than 2 alternatives
if ( test_expression1) {
statement1
} else if ( test_expression2) {
statement2
} else if ( test_expression3) {
statement3
} else {
statement4
}
The syntax of if…else statement is:
Only one statement will get executed depending upon the
test_expressions.
for(i in 1:30) {
if(i<=10){# i-th element of `u1` squared into `i`-th position of `usq`
usq[i] <- u1[i]*u1[i]
print(usq[i])
}else if(i>10 & < = 20){
usq[i] <- 2*u1[i]
print(usq[i])
}else{
usq[i]=0
}
}
Usq
1.199174587 0.001471373 1.488226525 0.641106497 0.001976277 0.146392429
[7] 0.146102733 0.003291107 2.735986866 3.312243036 -0.906243243 -0.6430
24231
[13] 0.330566852 -5.501139218 0.762957134 2.840590767 -0.508421993 4.7278
94961
[19] 2.252671368 -2.228362085 0.000000000 0.000000000 0.000000000 0.0000
00000
[25] 0.000000000 0.000000000 0.000000000 0.000000000 0.000000000 0.0000
00000
curve(3*x+2, 0, 3,xlim=c(0,6))
par(new=TRUE)
curve(2*x-.5*x^2,3,6,xlim=c(0,6), col = "violet")
x + *2x^2
2 80
2 * x3 -* 0.5
-6
0 1 2 3 4 5 6
u1 <- rnorm(30)
print("This loop calculates the square of the first 10 elements of vector u1")
# Initialize `usq`
usq <- 0
u1sum<-0
for(i in 1:10) {
# i-th element of `u1` squared into `i`-th position of `usq`
usq[i] <- u1[i]*u1[i]
print(usq[i])
}
1.199175
[1] 0.001471373
[1] 1.488227
[1] 0.6411065
[1] 0.001976277
[1] 0.1463924
[1] 0.1461027
[1] 0.003291107
[1] 2.735987
[1] 3.312243
for(i in 1:30) {
if(i<=10){# i-th element of `u1` squared into `i`-th position of `usq`
usq[i] <- u1[i]*u1[i]
print(usq[i])
}else{
usq[i] <- 2*u1[i]
print(usq[i])}
}
usq
[1] 1.199174587 0.001471373 1.488226525 0.641106497 0.001976277 0.146392429
[7] 0.146102733 0.003291107 2.735986866 3.312243036 -0.906243243 -0.643024231
[13] 0.330566852 -5.501139218 0.762957134 2.840590767 -0.508421993 4.727894961
[19] 2.252671368 -2.228362085 2.065822758 0.509759047 0.639117330 0.857311001
[25] 0.692543199 1.025886933 1.949234891 -1.185488173 -2.395137389 2.456806074
>