-
Notifications
You must be signed in to change notification settings - Fork 0
/
05-operadores.Rmd
235 lines (166 loc) · 8.44 KB
/
05-operadores.Rmd
1
2
3
4
5
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# Operadores
Los operadores son los símbolos que le indican a R que debe realizar una tarea. Combinando datos y operadores es que logramos que R haga su trabajo.
Existen operadores específicos para cada tipo de tarea. Los tipos de operadores principales son los siguientes:
* Aritméticos
* Relacionales
* Lógicos
* De asignación
Familiarizarnos con los operadores nos permitirá manipular y transformar datos de distintos tipos.
## Operadores aritméticos
Como su nombre lo indica, este tipo de operador es usado para operaciones aritméticas.
En R tenemos los siguientes operadores aritméticos:
Operador | Operación | Ejemplo | Resultado
---- |---- |---- |----
`+` | Suma | `5 + 3` | 8
`-` | Resta | `5 - 3` | 2
`*` | Multiplicación | `5 * 3` | 18
`/` | División | `5 /3` | 1.666667
`^` | Potencia | `5 ^ 3` | 125
`%%` | División entera | `5 %% 3`| 2
Es posible realizar operaciones aritméticas con datos de tipo **entero** y **numérico**.
Si escribes una operación aritmética en la consola de R y das *Enter*, esta se realiza y se devuelve su resultado.
```{r, echo=TRUE}
15 * 3
```
Cuando intentas realizar una operación aritmética con otro tipo de dato, R primero intentará coercionar ese dato a uno numérico. Si la coerción tiene éxito se realizará la operación normalmente, si falla, el resultado será un error.
Por ejemplo, `4 + "tres"` devuelve: `Error in 4 + "tres" : non-numeric argument for binary operator."`
```{r, echo=TRUE, error=TRUE}
4 + "tres"
```
El mensaje *"non-numeric argument for binary operator"* aparece siempre que intentas realizar una operación aritmética con un argumento no numérico. Si te encuentras un un error que contiene este mensaje, es la primera pista para que identifiques donde ha ocurrido un problema.
Cualquier operación aritmética que intentemos con un dato `NA`, devolverá `NA` como resultado.
```{r, echo = TRUE}
NA - 66
21 * NA
NA ^ 13
```
### La división entera
Entre los operadores aritméticos, el de división entera o **módulo** requiere una explicación adicional sobre su uso. La operación que realiza es una división de un número entre otro, pero en lugar de devolver el cociente, nos devuelve el residuo.
Por ejemplo, si hacemos una división entera de 4 entre 2, el resultado será 0. Esta es una división exacta y no tiene residuo.
```{r, echo =TRUE}
4 %% 2
```
En cambio, si hacemos una división entera de 5 entre 2, el resultado será 1, pues este es el residuo de la operación.
```{r, echo =TRUE}
5 %% 2
```
## Operadores relacionales
Los operadores lógicos son usados para hacer comparaciones y siempre devuelven como resultado `TRUE` o `FALSE` (verdadero o falso, respectivamente).
Operador| Comparación | Ejemplo | Resultado
---- |---- |---- |----
`<` | Menor que | `5 < 3` | `FALSE`
`<=` | Menor o igual que | `5 <= 3` | `FALSE`
`>` | Mayor que | `5 > 3` | `TRUE`
`>=` | Mayor o igual que | `5 >= 3` | `TRUE`
`==` | Exactamente igual que | `5 == 3` | `FALSE`
`!=` | No es igual que | `5 != 3` | `TRUE`
Es posible comparar cualquier tipo de dato sin que resulte en un error.
Sin embargo, al usar los operadores `>`, `>=`, `<` y `<=` con cadenas de texto, estos tienen un comportamiento especial.
Por ejemplo, `"casa" > "barco"` nos devuelve `TRUE`.
```{r}
"casa" > "barco"
```
Este resultado se debe a que se ha hecho una comparación por orden alfabético. En este caso, la palabra "casa" tendría una posición posterior a "barco", pues empieza con "c" y esta letra tiene una posición posterior a la "b" en el alfabeto. Por lo tanto, es verdadero que sea "mayor".
Cuando intentamos comparar factores, siempre obtendremos como resultado `NA` y una advertencia acerca de que estos operadores no son significativos para datos de tipo factor.
```{r, echo=TRUE}
as.factor("casa") > "barco"
```
## Operadores lógicos
Los operadores lógicos son usados para operaciones de **álgebra Booleana**, es decir, para describir relaciones lógicas, expresadas como verdadero (`TRUE`) o falso (`FALSO`).
Operador | Comparación | Ejemplo | Resultado
---- |---- |---- |----
`x | y` | x Ó y es verdadero | `TRUE | FALSE` | `TRUE`
`x & y` | x Y y son verdaderos | `TRUE & FALSE` | `FALSE`
`!x` | x no es verdadero (negación) | `!TRUE` | `FALSE`
`isTRUE(x)` | x es verdadero (afirmación) | `isTRUE(TRUE)` | `TRUE`
Los operadores `|` y `&` siguen estas reglas:
* `|` devuelve `TRUE` si alguno de los datos es `TRUE`
* `&` solo devuelve `TRUE` si ambos datos es `TRUE`
* `|` solo devuelve `FALSE` si ambos datos son `FALSE`
* `&` devuelve `FALSE` si alguno de los datos es `FALSE`
Estos operadores pueden ser usados con estos con datos de tipo **numérico**, **lógico** y **complejo**. Al igual que con los operadores relacionales, los operadores lógicos siempre devuelven `TRUE` o `FALSE`.
Para realizar operaciones lógicas, todos los valores numéricos y complejos distintos a `0` son coercionados a `TRUE`, mientras que `0` siempre es coercionado a `FALSE`.
Por ejemplo, `5 | 0` resulta en `TRUE` y `5 & FALSE` resulta en `FALSE`. Podemos comprobar lo anterior con la función `isTRUE()`.
```{r, echo=TRUE}
5 | 0
5 & 0
isTRUE(0)
isTRUE(5)
```
Estos operadores se pueden combinar para expresar relaciones complejas.
Por ejemplo, la negación `FALSE` Y `FALSE` dará como resultado `TRUE`.
```{r, }
!(FALSE | FALSE)
```
También podemos combinar operadores lógicos y relacionales, dado que esto últimos dan como resultado `TRUE` y `FALSE`.
```{r, echo=FALSE}
(4 < 6) | (6 == 6)
```
## Operadores de asignación
Este es probablemente el operador más importante de todos, pues nos permite asignar datos a variables.
Operador | Operación
---- |----
`<-` | Asigna un valor a una variable
`=` | Asigna un valor a una variable
Aunque podemos usar el signo igual para una asignación, a lo largo de este libro utilizaremos `<-`, por ser característico de R y fácil de reconocer visualmente.
Después de realizar la operación de asignación, podemos usar el nombre de la variable para realizar operaciones con ella, como si fuera del tipo de datos que le hemos asignado. Si asignamos un valor a una variable a la que ya habíamos asignado datos, nuestra variable conserva el valor más reciente.
Además, esta operación nos permite "guardar" el resultado de operaciones, de modo que los podemos recuperar sin necesidad de realizar las operaciones otra vez. Basta con llamar el nombre de la variable en la consola
En este ejemplo, asignamos valores a las variables `estatura` y `peso`.
```{r, echo=TRUE}
estatura <- 1.73
peso <- 83
```
Llamamos a sus valores asignados
```{r, echo=TRUE}
estatura
peso
```
Usamos los valores asignados para realizar operaciones.
```{r, echo=TRUE}
peso / estatura ^ 2
```
Cambiamos el valor de una variable a uno nuevo y realizamos operaciones
```{r, echo=TRUE}
peso <- 76
peso
peso / estatura ^ 2
estatura <- 1.56
peso <- 48
peso / estatura ^ 2
```
Asignamos el resultado de una operación a una variable nueva.
```{r, echo = TRUE}
bmi <- peso / estatura ^ 2
bmi
```
Como podrás ver, es posible asignar a una variable valores de otra variable o el resultado de operaciones con otras variables.
```{r, echo=TRUE}
velocidad_inicial <- 110
velocidad_final <- 185
tiempo_inicial <- 0
tiempo_final <- 15
variacion_velocidad <- velocidad_final - velocidad_inicial
variacion_tiempo <- tiempo_final - tiempo_inicial
variacion_velocidad / variacion_tiempo
```
## Orden de operaciones
En R, al igual que en matemáticas, las operaciones tienen un orden de evaluación definido.
Cuanto tenemos varias operaciones ocurriendo al mismo tiempo, en realidad, algunas de ellas son realizadas antes que otras y el resultado de ellas dependerá de este orden.
El orden de operaciones incluye a las aritméticas, relacionales, lógicas y de asignación.
En la tabla siguiente se presenta el orden en que ocurren las operaciones que hemos revisado en este capítulo.
Orden | Operadores
--- |---
1 | `^`
2 | `*` `/`
3 | `+` `-`
4 | `<` `>` `<=` `>=` `==` `!=`
5 | `!`
6 | `&`
7 | `|`
8 | `<-`
Si deseamos que una operación ocurra antes que otra, rompiendo este orden de evaluación, usamos paréntesis.
```{r}
```
Podemos tener paréntesis anidados.
```{r}
```