Guide To Programming And Algorithms Using R Ozgur Ergul Ergl pdf download
Guide To Programming And Algorithms Using R Ozgur Ergul Ergl pdf download
https://ebookbell.com/product/guide-to-programming-and-
algorithms-using-r-ozgur-ergul-ergl-38077146
https://ebookbell.com/product/guide-to-competitive-programming-
learning-and-improving-algorithms-through-contests-antti-
laaksonen-6819210
https://ebookbell.com/product/guide-to-competitive-programming-
learning-and-improving-algorithms-through-contests-3rd-edition-3rd-
edition-antti-laaksonen-58762872
https://ebookbell.com/product/guide-to-competitive-programming-
learning-and-improving-algorithms-through-contests-58775048
https://ebookbell.com/product/linear-programming-and-algorithms-for-
communication-networks-a-pratical-guide-to-network-design-control-and-
management-eiji-oki-36520672
Linear Programming And Algorithms For Communication Networks A
Practical Guide To Network Design Control And Management Eiji Oki
https://ebookbell.com/product/linear-programming-and-algorithms-for-
communication-networks-a-practical-guide-to-network-design-control-
and-management-eiji-oki-4348400
https://ebookbell.com/product/linear-programming-and-algorithms-for-
communication-networks-a-practical-guide-to-network-design-control-
and-management-eiji-oki-4421856
https://ebookbell.com/product/a-commonsense-guide-to-data-structures-
and-algorithms-level-up-your-core-programming-skills-2nd-edition-jay-
wengrow-23508066
https://ebookbell.com/product/a-commonsense-guide-to-data-structures-
and-algorithms-in-python-volume-1-level-up-your-core-programming-
skills-jay-wengrow-57742868
Özgür Ergül
Guide to
Programming
and Algorithms
Using R
www.it-ebooks.info
Guide to Programming and Algorithms
Using R
www.it-ebooks.info
Özgür Ergül
Guide to
Programming
and Algorithms
Using R
www.it-ebooks.info
Özgür Ergül
Electrical and Electronics Engineering
Middle East Technical University
Ankara, Turkey
www.it-ebooks.info
Dedication
01 dedicate = function(reader){
02 if (reader == mywife){
03 print("To my wife...")
04 }
05 else if (reader == myparents){
06 print("To my parents...")
07 }
08 else{
09 print("To all programmers...")
10 }
11 }
www.it-ebooks.info
Preface
vii
www.it-ebooks.info
viii Preface
When it comes to the point where I need to tell what is special about this book,
I would describe it as a simple, concise, and short material that may be suitable for
introductory programming courses. Some of the discussions in the text may be found
as “stating the obvious” by many lecturers and instructors, but in fact, I have col-
lected them from my discussions with students, and they actually include answers
to those questions that students are often embarrassed to ask. I have also filtered
topics such that only threshold concepts, which are major barriers in learning com-
puter programming, are considered in this book. I believe that higher-level topics
can easily be understood once the topics focused in this book are covered.
This book contains nine chapters. The first chapter is an introduction, where we
start with simple examples to understand programming and algorithms. The second
and third chapters present two important concepts of programming, namely loops
and recursions. We consider various example programs, including those with mis-
takes that are commonly experienced by beginners. In the fourth chapter, we focus
on the efficiency of programs and algorithms. This topic is unfortunately omitted or
skipped fast in some programming courses and books, but in fact, it is required to
understand why we are programming. Another important aspect, i.e., accuracy, is
focused in the fifth chapter. A major topic in computer programming, namely, sort-
ing is discussed in the sixth chapter, followed by the seventh chapter that is devoted
to linear systems of equations. In the eighth chapter, we briefly discuss file process-
ing, i.e., investigating and modifying simple files. Finally, the last chapter presents
some mini projects that students may enjoy while programming.
As the title of this book suggests, all programs given in this book are written in
the R language. This is merely a choice, which is supported by some of its favor-
able properties, such as being freely available and easy to use. Even though a single
language is used throughout the book, no strict assumptions have been made so that
all discussions are also valid for other programming languages. Except the last one,
each chapter ends with a set of exercises that needs to be completed for fully under-
standing the given topics because programming and algorithms cannot be learned
without evaluating, questioning, and discussing the material in an active manner via
hands-on practices.
Enjoy it!
Ankara, Turkey Özgür Ergül
www.it-ebooks.info
Contents
1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1 Programming Concept . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Example: An Omelette-Cooking Algorithm . . . . . . . . . . . . . 2
1.3 Common Properties of Computer Programs . . . . . . . . . . . . . 4
1.4 Programming in R Using Functions . . . . . . . . . . . . . . . . . 4
1.4.1 Working with Conditional Statements . . . . . . . . . . . . 6
1.5 Some Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.6 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.1 Loop Concept . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.1.1 Example: 1-Norm with For Statement . . . . . . . . . . . . 13
2.1.2 Example: 1-Norm with While Statement . . . . . . . . . . 16
2.1.3 Example: Finding the First Zero . . . . . . . . . . . . . . . 19
2.1.4 Example: Infinity Norm . . . . . . . . . . . . . . . . . . . 22
2.2 Nested Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.2.1 Example: Matrix–Vector Multiplication . . . . . . . . . . . 23
2.2.2 Example: Closest-Pair Problem . . . . . . . . . . . . . . . 26
2.3 Iteration Concept . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.3.1 Example: Number of Terms for e . . . . . . . . . . . . . . 28
2.3.2 Example: Geometric Series . . . . . . . . . . . . . . . . . 30
2.3.3 Example: Babylonian Method . . . . . . . . . . . . . . . . 30
2.4 Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3 Recursions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.1 Recursion Concept . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.1.1 Example: Recursive Calculation of 1-Norm . . . . . . . . . 35
3.1.2 Example: Fibonacci Numbers . . . . . . . . . . . . . . . . 40
3.1.3 Example: Factorial . . . . . . . . . . . . . . . . . . . . . . 41
3.2 Using Recursion for Solving Problems . . . . . . . . . . . . . . . 42
3.2.1 Example: Highest Common Factor . . . . . . . . . . . . . 42
3.2.2 Example: Lowest Common Multiple . . . . . . . . . . . . 43
3.2.3 Example: Towers of Hanoi . . . . . . . . . . . . . . . . . 45
ix
www.it-ebooks.info
x Contents
www.it-ebooks.info
Contents xi
www.it-ebooks.info
Introduction
1
This introductory chapter starts with the programming concept, where we discuss
various aspects of programs and algorithms. We consider a simple omelette-cooking
algorithm to understand the basic principles of programming. Then, we list the com-
mon properties of computer programs, followed by some notes on programming in
R, particularly by using the function concept. Finally, matrices and vectors, as well
as their representations in R, are briefly discussed.
www.it-ebooks.info
2 1 Introduction
Assume that we would like to write an algorithm for cooking a simple omelette and
implement it as a program. As opposed to standard ones, these are to be executed
by humans. Let us simply list the basic steps.
• Gather eggs, crack them in a cup.
• Use a fork to mix them.
• Add salt, mix again.
• Pour butter onto a pan.
• Put the heat on. Wait until the butter melts.
• Pour the egg mixture onto the pan.
• Wait until there is no liquid visible.
This list can be considered as a program, since it is a sequence of commands and
instructions to effectively solve the omelette-cooking problem. Note that dividing
the third item into two parts as
• Add salt.
• Mix again.
would lead to another program, even though the algorithm (the underlying proce-
dure) would not change.
For this program to work smoothly, we need a cup, a fork, a pan, and heat. Under
normal circumstances, these items do not change. Hence, they can be called the
constants of the program. Of course, we can use a bowl instead of a cup to mix eggs.
This is perfectly allowed, but constants are considered to be fixed in the content of
the program, and changing them means modifying the program itself. Hence, using
a bowl instead of a cup would be writing another program, which could be more
suitable in some cases, e.g., for large numbers of eggs. Such a modification can
be minor (using bowl instead of cup) or major (adding pepper after salt). Making
www.it-ebooks.info
1.2 Example: An Omelette-Cooking Algorithm 3
www.it-ebooks.info
4 1 Introduction
In this book, all programs are written by using the R language, which is freely
available at
http://www.r-project.org/
This website also includes manuals and many notes on using R. Note that this book
is not an R guide; but we use this flexible language as a tool to implement algo-
rithms and to employ the resulting programs effectively for solving problems. All
programs investigated in this book can easily be rewritten by using other program-
ming languages since the underlying algorithms remain the same.
www.it-ebooks.info
1.4 Programming in R Using Functions 5
function_name = function(input1_name,input2_name,...){
some operations
some more operations
return(output_name)
}
function_name.R
to be used later. In order to use the function, we need to identify it in the R workspace
as
source("function_name.R")
after the working directory is set to the one where the file exists. Then, the function
can be executed simply by writing its name with appropriate inputs as
myoutput_name = function_name(myinput1_name,myinput2_name,...)
function_name(myinput1_name,myinput2_name,...)
also works, where the output is printed out rather than stored.
A function can be interpreted as a closed box where inputs are entering and
outputs are leaving. Users interact with a function only through inputs and out-
puts. Therefore, constants and variables used inside a function are not defined out-
side. Similarly, input and output names, e.g., input1_name, input2_name, and
output_name above, are considered to be defined inside the function, and they
are not available with the same names outside. This is the reason why we use my-
input1_name, myinput2_name, and myoutput_name above to distinguish
them from those used in the function.
The next subsection presents some examples that can be considered as warm-up
routines before writing and investigating more complicated functions in the next
chapters.
www.it-ebooks.info
6 1 Introduction
Let us write a simple program that gives the letter “a” if the input is 1 and the letter
“b” if the input is 2. Let the name of the program be giveletter. We can use
conditional statements to handle different cases.
01 giveletter = function(thenumber){
02 if (thenumber == 1){
03 theletter = "a"
04 }
05 if (thenumber == 2){
06 theletter = "b"
07 }
08 return(theletter)
09 }
After writing and saving the program above as giveletter.R, we can identify it as
source("giveletter.R")
and use it as
giveletter(2)
stores the result “b” in myletter, which is also defined outside the function. In
this context, mynumber and myletter can be considered as variables of the R
workspace, even though they are used for input/output.
Computer programs are often restricted to a range of inputs. For example, the
program above do not return an output if the input is 3. It may not be fair to ex-
pect from programmers to consider all cases (including user mistakes), but some-
times, such a limitation can be considered as a poor programming. Along this di-
rection, the program above can easily be improved by handling “other” cases as
follows.
www.it-ebooks.info
1.5 Some Conventions 7
01 giveletter = function(thenumber){
02 if (thenumber == 1){
03 theletter = "a"
04 }
05 else if (thenumber == 2){
06 theletter = "b"
07 }
08 else{
09 theletter = " "
10 }
11 return(theletter)
12 }
The revised program returns the space character if the input is neither 1 nor 2. Note
that, in such a case, the original program gives an error and does not produce any
useful feedback to the user. If the input is not a number (as a mistake), the revised
program also gives an error, which may further be handled with additional checks in
the program, if desired. Obviously, for any program, there is a tradeoff between the
applicability and simplicity that must be considered carefully by the programmer.
Once a function is written, it can also be used inside another function, provided
that it is defined in the R workspace. This increases the reusability of functions
and creates a flexible implementation environment, where complicated functions
are constructed by using more basic functions. Note that the R language has also
many built-in functions that can be used easily when writing programs.
www.it-ebooks.info
8 1 Introduction
defines a vector of 16 elements with 1, 4, 7, and 10 are repeated four times. Similarly,
A = matrix(0,nrow=16,ncol=16)
B = A[k1 : k1 , l1 : l2 ] = A[k, l1 : l2 ],
means that some rows and columns of a matrix A are selected and stored in another
matrix B.
www.it-ebooks.info
1.6 Conclusions 9
1.6 Conclusions
Computer programs are written for solving problems on computers. Each program
has input(s) and output(s) and is based on an algorithm that describes the proce-
dure to attack and solve a given problem. Efficiency and accuracy are two aspects
that should be considered carefully when implementing algorithms and writing pro-
grams. In addition to inputs and outputs, programs often contain constants and vari-
ables that are not visible to users. Each of these items (inputs, outputs, constants,
and variables) can be a scalar, vector, or matrix.
In the next chapters, we will consider R programs written as functions to solve
various practical problems. In addition to correct versions, we will investigate incor-
rect and poor programs that contain possible mistakes and limitations to be avoided
along the direction of good programming.
1.7 Exercises
1. Do the following list of operations in the R workspace:
i = 5
j = 6
k = i + j
print(k)
j = j + 2
k = k + j
print(k)
k = k*k
print(k)
Observe how the value of k (via outputs of the print statements) changes.
2. Write the following program, which finds and returns the larger one of two given
numbers:
01 givelarger = function(i,j){
02 if (i > j){
03 thelarger = i
04 }
05 else{
06 thelarger = j
07 }
08 return(thelarger)
09 }
Test your program (after saving and sourcing it) for various inputs, such as
givelarger(3,-4)
3. Write the following program, which also finds and returns the larger one of two
given numbers:
www.it-ebooks.info
Another Random Scribd Document
with Unrelated Content
—Sí, ahora mismo.
—¿Cuento con que escribirás esas cartas?
—Sí.
—Bueno; me voy, que tengo que comprar unos cristales. ¡Háblale al
chico!
—Descuida.
—Gracias por todo. Y vete por mi casa, ¿eh? Mira que de eso
depende mi porvenir y el de mi padre.
—Iré por allá.
Bernardo estrechó las manos de su amigo con efusión y se fué.
Roberto, al terminar de escribir, llamó:—Manuel.
—¿Qué?
—Estabas despierto, ¿eh?
—Sí señor.
—¿Has oído la conversación?
—Sí, señor.
—Pues si quieres, ya sabes. Ahí tienes un oficio que aprender.
—Iré, si le parece a usted bien.
—Lo que tú quieras.
—Entonces voy ahora mismo.
Manuel dejó la guardilla de Roberto sin despedirse de Alex y se
marchó en busca de Bernardo Santín, a la calle de Luchana. Era la
casa piso tercero, pero con el entresuelo y el principal resultaba
quinto. Llamó Manuel y le abrió un viejo de ojos encarnados, el
padre de Bernardo. Le explicó a lo que iba, y el viejo se encogió de
hombros y se fué a la cocina en donde estaba guisando. Manuel
esperó a que llegara Bernardo. La casa estaba todavía sin muebles;
sólo había una mesa y unos cuantos cacharros en la cocina y en un
cuarto grande dos camas. Llegó Bernardo, almorzaron los tres y
dispuso Santín que el muchacho pidiera una escalera al portero y se
dedicase a sujetar y a componer los cristales de la galería.
Después de dar estas órdenes, dijo que le esperaban y se fué.
Manuel el primer día se lo pasó en lo alto de una escalera sujetando
los cristales con listas de plomo y los rotos con tiras de papel.
Le costó mucho tiempo el arreglar los cristales; después Manuel
colocó las cortinas y empapeló la galería con papel continuo de color
azulado.
A la semana o cosa así apareció Roberto con los catálogos. Marcó
con lápiz las cosas necesarias que se habían de traer, y le dijo a
Bernardo cómo debía poner el laboratorio; le señaló un sitio en
donde era conveniente hacer un tragaluz para poner las placas al sol
y sacar las positivas, y le indicó otra porción de cosas. Bernardo se
fijó en lo que le decía, y transmitió el encargo a Manuel. Bernardo,
además de ser poco inteligente, era un gandul completo. No hacía
absolutamente nada. Sólo cuando venía su novia a ver cómo
marchaban los trabajos, fingía estar atareado.
Era la novia muy simpática; a Manuel le pareció hasta bonita, a
pesar de tener el pelo rojo, y las pestañas y las cejas del mismo
color. Tenía una carita blanca, algo pecosa, la nariz sonrosada,
respingona, los ojos claros y los labios tan rojos y tan bonitos que
despertaban el deseo de besarlos. Era de pequeña estatura, pero
estaba muy bien formada. Hablaba rozando las erres y convirtiendo
las ces en eses.
Parecía bastante enamorada de Bernardo, lo que a Manuel le chocó.
—Es que no le conoce—pensó.
Bernardo, con un convencimiento absoluto de su propia ciencia, le
explicaba a la muchacha los trabajos que hacía, cómo iba a poner el
laboratorio. Lo que oía a Roberto se lo espetaba a su novia con un
descaro inaudito. La muchacha lo encontraba todo muy bien; sin
duda se prometía un porvenir risueño.
Manuel, que comprendía el timo que estaba dando Bernardo,
pensaba si no sería una obra de caridad advertirle a la rubia que su
novio era un zascandil que no servía para nada, pero ¡quién le metía
a él en esto!
Bernardo se llevaba la gran vida; paseaba, compraba alhajas en las
casas de préstamos, jugaba en el Frontón Central. Si algo hacía en
casa era dar disposiciones contradictorias y embarullarlo todo.
Mientras tanto el padre, indiferente, guisaba en la cocina y se
pasaba el día entero machacando en el almirez o picando en el tajo.
Manuel iba a la cama tan cansado que se dormía enseguida; pero
una noche en que no se durmió tan pronto, oyó en el otro cuarto a
Bernardo que decía:—Voy a mataros.
—¿Le mata?—preguntó la voz del viejo de los ojos encarnados.
—Espera—replicó el hijo—, me has interrumpido.
Y volvió a comenzar nuevamente la lectura, porque no se trataba
más que de una lectura, hasta llegar otra vez al: Voy a mataros. En
las noches siguientes continuó Bernardo leyendo con un tono
terrible. Era éste sin duda su único trabajo.
Bernardo no tenía más preocupación que su padre; lo demás le era
completamente indiferente; le había sacado el dinero a su novia y
vivía con aquel dinero y lo gastaba como si fuera suyo. Cuando
llegaron la máquina y los demás artefactos de fotografía de
Alemania, al principio se entretuvo en impresionar placas que reveló
Roberto; pronto se aburrió de esto y no hizo nada.
Era torpe y bruto hasta la exageración; no hacía más que
necedades, abrir la linterna cuando se estaban revelando las placas,
confundir los frascos. Roberto se exasperaba al ver que no ponía
ningún cuidado.
Mientras tanto adelantaban los preparativos de la boda, Manuel y
Bernardo fueron varias mañanas al Rastro y compraron fotografías
de actrices hechas en París por Reutlinger, despegaron de la
cartulina el retrato y lo volvieron a pegar en otros cartones con la
firma Bernardo Santín, fotógrafo, puesta al margen con letras
doradas.
En noviembre se celebró la boda en la iglesia de Chamberí. Roberto
no quiso asistir; pero el mismo Bernardo fué a buscarle a casa y no
tuvo más remedio que tomar parte en la fiesta. Después de la
ceremonia fueron a comer a un café de la Glorieta de Bildao.
Los comensales eran: dos amigos del padre del novio, uno de ellos
militar retirado; la patrona en cuya casa vivía la novia, con su hija;
un primo de Bernardo, su mujer y Manuel.
Roberto comenzó a hablar con la novia y le pareció muy simpática y
agradable; hablaba muy bien el inglés y cambiaron los dos algunas
frases en este idioma.
—Es una lástima que se case con este mastuerzo—pensó Roberto.
En la comida uno de los viejos comenzó a soltar una porción de
indecencias que hicieron ruborizar a la novia. Bernardo, que bebió
demasiado, dió bromas a la mujer de su primo y lo hizo con la
pesadez y la falta de gracia que le caracterizaba.
La vuelta de la boda a la casa, al anochecer, fué melancólica.
Bernardo se sentía valiente y quería hacer graciosidades. Esther
hablaba con Roberto de su madre que había muerto, de la soledad
en que vivía.
Al llegar al portal se despidieron los invitados de los novios, y al ir a
marcharse Roberto, Bernardo se le acercó y con voz apagada y débil
le confesó que tenía miedo de quedarse solo con su mujer.
—Hombre, no seas idiota. Entonces, ¿para qué te has casado?
—No sabía lo que hacía. Anda, acompáñame un momento.
—Pues ¡vaya una gracia que le haría a tu mujer!
—Sí, le eres muy simpático.
Roberto contempló con atención a su amigo y no le miró la frente
porque no le gustaban las bromas.
—Sí, hombre, acompáñame. Hay otra cosa además.
—¿Pues qué hay?
—Que no sé aún nada de fotografía y quisiera que vinieras una
semana o dos. ¡Por favor te lo pido!
—No puede ser, yo tengo que dar mis lecciones.
—Ven aunque no sea más que a la hora de comer. Comerás con
nosotros.
—Bueno.
—Y ahora sube un instante, por favor.
—No, ahora no subo—, y Roberto dió media vuelta y se fué.
En los días posteriores Roberto fué a casa del recién casado y charló
un rato con el matrimonio durante la comida.
Al tercer día entre Bernardo y Manuel retrataron a dos criadas que
aparecieron por la fotografía. Roberto reveló los clichés que por
casualidad salieron bien, y siguió acudiendo a casa de su amigo.
Bernardo continuaba haciendo la misma vida de antes de casado,
dedicándose a pasear y divertirse. A los pocos días no se presentó a
la hora de comer. Tenía una falta de sentido moral absoluta; había
notado que su mujer y Roberto simpatizaban y pensó que éste, por
seguir adelante y hacerle el amor a su mujer, trabajaría en su lugar.
Con tal de que su padre y él viviesen bien, lo demás no le importaba
nada.
Cuando lo comprendió Roberto, se indignó.
—Pero, oye tú—le dijo—¿Es que tú crees que yo voy a trabajar por
ti, mientras tú andas golfeando? Quia, hombre.
—Yo no sirvo para estas porquerías de reactivos—replicó Bernardo
malhumorado—, yo soy un artista.
—Lo que tú eres es un imbécil que no sirve para nada.
—Bueno, mejor.
—Es indigno. Te has casado con esa muchacha para quitarle los
pocos cuartos que tenía. Da asco.
—Si ya sé yo que tu defenderás a mi mujer.
—No, hombre, yo no la defiendo. Ella ha sido también bastante
idiota la pobre para casarse contigo.
—¿Eso quiere decir que ya no quieres venir a trabajar?
—Claro que no.
—Pues me tiene sin cuidado. He encontrado un socio industrial. De
manera que ya sabes; yo a nadie le pido que venga a mi casa.
—Está bien. Adiós.
Dejó Roberto de aparecer por la casa; a los pocos días se presentó
el socio y Bernardo despidió a Manuel.
CAPÍTULO III
LA EUROPEA
agencia de negocios y de colocaciones
de
Bonifacio de Mingote
LA BENEFACTORA
agencia médico-farmacéutica
de
ebookbell.com