Este notebook es la traducción completa a R del notebook original de Python
1_Fundamentos_Python.ipynb. Como R es, igual que Python, un lenguaje “vectorizado” por naturaleza, muchas operaciones que en Python requierennumpy(arrays, vectorización) son nativas de R: los vectores y matrices de R ya operan elemento a elemento sin librerías adicionales.
| Operador | Operación | Ejemplo | Resultado |
|---|---|---|---|
+ |
Suma | 3 + 5 |
8 |
- |
Resta | 10 - 4 |
6 |
* |
Multiplicación | 6 * 7 |
42 |
/ |
División real | 17 / 5 |
3.4 |
%/% |
División entera | 17 %/% 5 |
3 |
%% |
Módulo (resto) | 17 %% 5 |
2 |
^ |
Potencia | 2 ^ 10 |
1024 |
## [1] 8
## [1] 6
## [1] 95
## [1] 42
## [1] 3.4
## [1] 3
## [1] 2
## [1] 1024
## [1] 27
## [1] 5
## [1] 2
## [1] 14
## [1] 20
## [1] 512
¡Cuidado! A diferencia de Python (
2**3**2 = 512, asociativo por la derecha), en R el operador^es asociativo por la izquierda:2^3^2se evalúa como(2^3)^2 = 64. Si se quiere el resultado 512, hay que escribir2^(3^2).
## [1] 512
| Operador | Significado |
|---|---|
== |
Igual a |
!= |
Diferente de |
>, < |
Mayor / menor que |
>=, <= |
Mayor o igual / menor o igual |
## [1] TRUE
## [1] TRUE
## [1] TRUE
## [1] TRUE
## [1] FALSE
| Operador | Significado |
|---|---|
&& / & |
Ambos deben ser TRUE
(&& para un solo valor, &
vectorizado) |
\|\| / \| |
Al menos uno debe ser TRUE |
! |
Niega el valor |
## [1] TRUE
## [1] FALSE
## [1] TRUE
## [1] FALSE
## [1] TRUE
| Tipo | Nombre en R | Ejemplo |
|---|---|---|
| Entero | integer |
x <- 10L |
| Decimal | double (o numeric) |
pi_val <- 3.14159 |
| Texto | character |
nombre <- 'Juan' |
| Booleano | logical |
activo <- TRUE |
| Nulo | NULL / NA |
vacio <- NULL |
# Asignación de variables (se recomienda "<-" en R, aunque "=" también funciona)
x <- 10
pi_val <- 3.14159
nombre <- "María"
activo <- TRUE
print(c(x, pi_val))## [1] 10.00000 3.14159
## [1] "María"
## [1] TRUE
## [1] "numeric"
## [1] "numeric"
## [1] "character"
## [1] "logical"
# Asignación múltiple (R no la tiene nativa; se simula con una lista)
vals <- c(a = 5, b = 10, c = 15)
a <- vals["a"]; b <- vals["b"]; c_ <- vals["c"]
print(c(a, b, c_))## a b c
## 5 10 15
## b a
## 10 5
## [1] 7
## [1] "7"
## [1] 3
## [1] 42
# sprintf(): insertar variables dentro de texto (equivalente a los f-strings de Python)
nombre <- "Carlos"; edad <- 22; nota <- 15.7
cat(sprintf("%s tiene %d años y su nota es %.1f\n", nombre, edad, nota))## Carlos tiene 22 años y su nota es 15.7
## Nota redondeada: 15.7
## Porcentaje: 78.50%
R no tiene operadores como +=,
-=, *=, /= de forma nativa; se
escriben explícitamente.
## [1] 150
## [1] 300
## [1] 42
| Función/método | Qué hace | Ejemplo |
|---|---|---|
toupper() |
Mayúsculas | toupper('hola') → 'HOLA' |
tolower() |
Minúsculas | tolower('HOLA') → 'hola' |
gsub() |
Reemplazar | gsub('g','p','gato') →
'pato' |
strsplit() |
Dividir | strsplit('a,b,c', ',') |
nchar() |
Longitud | nchar('Python') → 6 |
## [1] 17
## [1] "ESTADÍSTICA CON R"
## [1] "Estadística" "con" "R"
# Indexación de caracteres (R no tiene indexación directa como Python; se usa substr())
print(substr(texto, 1, 1)) # primer carácter## [1] "E"
## [1] "R"
## [1] "Estadística"
| Estructura Python | Equivalente en R | Mutable | Ordenada |
|---|---|---|---|
Lista [...] |
vector (homogéneo) o list
(heterogéneo) |
✅ | ✅ |
Tupla (...) |
vector con c() (no hay
inmutabilidad estricta) |
— | ✅ |
Diccionario {clave: valor} |
list con nombres, o
named vector |
✅ | ✅ |
Conjunto {...} |
unique(vector) + funciones
union/intersect/setdiff |
✅ | ❌ |
## [1] 14 16 12 18 15
## Longitud: 5
## [1] 14
## [1] 15
## [1] 16 12
# Funciones sobre vectores (equivalentes a los métodos de listas de Python)
notas <- c(notas, 20) # append
notas <- c(10, notas) # insertar al inicio
notas <- sort(notas) # ordenar
print(notas)## [1] 10 12 14 15 16 18 20
## [1] 105
## [1] 10
## [1] 20
## [1] 15
# "List comprehension" -> en R se hace con sapply()/vectorización directa
cuadrados <- (1:10)^2
print(cuadrados)## [1] 1 4 9 16 25 36 49 64 81 100
## [1] 0 2 4 6 8 10 12 14 16 18
# En R no existe una tupla inmutable nativa; se usa un vector o lista normal
coordenada <- c(3.5, 7.2)
print(coordenada[1])## [1] 3.5
## [1] 7.2
## x = 3.5, y = 7.2
estudiante <- list(
nombre = "Ana",
edad = 21,
carrera = "Ingeniería",
notas = c(15, 17, 14, 18)
)
print(estudiante$nombre)## [1] "Ana"
## [1] 15 17 14 18
## $nombre
## [1] "Ana"
##
## $edad
## [1] 22
##
## $carrera
## [1] "Ingeniería"
##
## $notas
## [1] 15 17 14 18
##
## $semestre
## [1] 6
# Recorrer una lista con nombres
for (clave in names(estudiante)) {
cat(sprintf("%10s: %s\n", clave, paste(estudiante[[clave]], collapse = ", ")))
}## nombre: Ana
## edad: 22
## carrera: Ingeniería
## notas: 15, 17, 14, 18
## semestre: 6
if, else if, elsenota <- 14
if (nota >= 18) {
print("Excelente")
} else if (nota >= 14) {
print("Bueno")
} else if (nota >= 11) {
print("Regular")
} else {
print("Desaprobado")
}## [1] "Bueno"
# Condicional en una línea (equivalente al ternario de Python)
nota <- 16
resultado <- if (nota >= 11) "Aprobado" else "Desaprobado"
cat(sprintf("Nota %d: %s\n", nota, resultado))## Nota 16: Aprobado
forfrutas <- c("manzana", "plátano", "uva", "naranja")
for (fruta in frutas) {
cat(sprintf("Me gusta la %s\n", fruta))
}## Me gusta la manzana
## Me gusta la plátano
## Me gusta la uva
## Me gusta la naranja
## 0 1 2 3 4
## 2 4 6 8
# seq_along(): índice + valor (equivalente a enumerate)
notas <- c(14, 16, 12, 18, 15)
for (i in seq_along(notas)) {
estado <- if (notas[i] >= 14) "\u2713" else "\u2717"
cat(sprintf("Alumno %d: %d %s\n", i, notas[i], estado))
}## Alumno 1: 14 ✓
## Alumno 2: 16 ✓
## Alumno 3: 12 ✗
## Alumno 4: 18 ✓
## Alumno 5: 15 ✓
# Función básica
saludar <- function(nombre) {
return(paste0("¡Hola, ", nombre, "!"))
}
print(saludar("María"))## [1] "¡Hola, María!"
## [1] "¡Hola, Carlos!"
# Función con valor por defecto
potencia <- function(base, exponente = 2) {
return(base ^ exponente)
}
print(potencia(5)) # 25 (exponente=2 por defecto)## [1] 25
## [1] 125
## [1] 1024
# Función estadística: media aritmética
media <- function(datos) {
return(sum(datos) / length(datos))
}
notas <- c(14, 16, 12, 18, 15)
cat(sprintf("Media = %.2f\n", media(notas)))## Media = 15.00
# Función que retorna múltiples valores (con una lista, como en Python con tuplas)
estadisticas <- function(datos) {
n <- length(datos)
prom <- sum(datos) / n
varianza <- sum((datos - prom)^2) / (n - 1)
desv <- sqrt(varianza)
return(list(media = prom, varianza = varianza, desv = desv))
}
res <- estadisticas(c(14, 16, 12, 18, 15))
cat(sprintf("Media=%.2f, Var=%.2f, Desv=%.2f\n", res$media, res$varianza, res$desv))## Media=15.00, Var=5.00, Desv=2.24
# Función anónima (lambda) — sintaxis moderna de R (>= 4.1): \(x) x^2
cuadrado <- \(x) x^2
cubo <- \(x) x^3
print(cuadrado(7)) # 49## [1] 49
## [1] 27
## [1] 1 8 27 64 125
En Python se necesita numpy para vectorizar operaciones;
en R, los vectores ya son vectorizados de forma nativa.
No se requiere ninguna librería adicional.
| Concepto | Vector Python (lista) | Vector R |
|---|---|---|
| Velocidad | Lenta sin numpy | Rápida (nativa) |
| Operaciones | Elemento por elemento manual | Vectorizadas de forma nativa |
| Tipos de dato | Mixtos | Homogéneos dentro de un vector |
## Vector: 1 2 3 4 5
## Tipo: numeric
## Longitud: 5
## [1] 0 0 0 0 0
## [1] 1 1 1 1
## [1] 0 2 4 6 8
## [1] 0.00 0.25 0.50 0.75 1.00
# Operaciones vectorizadas (se aplican a TODOS los elementos, nativamente)
a <- c(10, 20, 30, 40, 50)
print(a + 5)## [1] 15 25 35 45 55
## [1] 20 40 60 80 100
## [1] 100 400 900 1600 2500
## [1] 3.162278 4.472136 5.477226 6.324555 7.071068
## [1] 11 22 33 44 55
## [1] 10 40 90 160 250
## [1] 10 10 10 10 10
# Funciones estadísticas
datos <- c(14, 16, 12, 18, 15, 11, 17, 13)
cat(sprintf("Media: %.2f\n", mean(datos)))## Media: 14.50
## Mediana: 14.50
## Desv: 2.45
## Var: 6.00
## Suma: 116
## Min: 11
## Max: 18
## sin: 0 0.5 0.7071 0.866 1
## cos: 1 0.866 0.7071 0.5 0
## exp: 1 2.718282 7.389056 20.08554
## log: 0 1 2
## pi = 3.1415926536
## e = 2.7182818285
## Matriz A (3×3):
## [,1] [,2] [,3]
## [1,] 1 2 3
## [2,] 4 5 6
## [3,] 7 8 9
## Identidad 3x3:
## [,1] [,2] [,3]
## [1,] 1 0 0
## [2,] 0 1 0
## [3,] 0 0 1
##
## Matriz de ceros 2x4:
## [,1] [,2] [,3] [,4]
## [1,] 0 0 0 0
## [2,] 0 0 0 0
##
## Matriz de unos 3x2:
## [,1] [,2]
## [1,] 1 1
## [2,] 1 1
## [3,] 1 1
| Operación | Símbolo | Descripción |
|---|---|---|
| Suma | A + B |
Elemento a elemento |
| Producto elemento | A * B |
Elemento a elemento |
| Producto matricial | A %*% B |
Multiplicación de matrices |
| Transpuesta | t(A) |
Intercambiar filas ↔︎ columnas |
| Inversa | solve(A) |
\(A^{-1}\) |
| Determinante | det(A) |
\(\|A\|\) |
A <- matrix(c(1, 3, 2, 4), nrow = 2, byrow = TRUE)
B <- matrix(c(5, 7, 6, 8), nrow = 2, byrow = TRUE)
cat("A + B (suma):\n"); print(A + B)## A + B (suma):
## [,1] [,2]
## [1,] 6 10
## [2,] 8 12
##
## A * B (elemento a elemento):
## [,1] [,2]
## [1,] 5 21
## [2,] 12 32
##
## A %*% B (producto matricial):
## [,1] [,2]
## [1,] 23 31
## [2,] 34 46
## A:
## [,1] [,2]
## [1,] 1 3
## [2,] 2 4
##
## A^T (transpuesta):
## [,1] [,2]
## [1,] 1 2
## [2,] 3 4
## det(A) = -2.00
##
## A^-1:
## [,1] [,2]
## [1,] -2 1.5
## [2,] 1 -0.5
##
## A %*% A^-1 (debe ser I):
## [,1] [,2]
## [1,] 1 0
## [2,] 0 1
# Sistema de ecuaciones lineales: Ax = b
# 2x + 3y = 13
# 4x + y = 11
A_sys <- matrix(c(2, 4, 3, 1), nrow = 2) # por columnas: col1=(2,4), col2=(3,1)
b_sys <- c(13, 11)
x_sol <- solve(A_sys, b_sys)
cat(sprintf("Solución: x = %.2f, y = %.2f\n", x_sol[1], x_sol[2]))## Solución: x = 2.00, y = 3.00
## Verificación: A·x = 13 11 (debe ser 13 11 )
# Valores y vectores propios
M <- matrix(c(4, 1, 2, 3), nrow = 2)
eig_M <- eigen(M)
cat("Valores propios:", eig_M$values, "\n")## Valores propios: 5 2
## Vectores propios:
## [,1] [,2]
## [1,] 0.8944272 -0.7071068
## [2,] 0.4472136 0.7071068
# Ejemplo: resolver un sistema 3x3
# x + 2y + z = 9
# 2x + y + 3z = 14
# 3x + y + 2z = 13
A3 <- matrix(c(1,2,3, 2,1,1, 1,3,2), nrow = 3) # columnas: (1,2,3),(2,1,1),(1,3,2)
b3 <- c(9, 14, 13)
sol3 <- solve(A3, b3)
cat(sprintf("x=%.2f, y=%.2f, z=%.2f\n", sol3[1], sol3[2], sol3[3]))## x=1.75, y=2.25, z=2.75
## Verificación: 9 14 13 = 9 14 13
x <- seq(-5, 5, length.out = 100)
plot(x, 2*x + 1, type = "l", col = C["azul"], lwd = 2,
xlab = "x", ylab = "y", main = "Funciones Lineales: y = mx + b", font.main = 2)
lines(x, -x + 3, col = C["rojo"], lwd = 2)
lines(x, 0.5*x, col = C["verde"], lwd = 2)
abline(h = 0, v = 0, lwd = 0.8)
legend("topleft", legend = c("y = 2x + 1", "y = -x + 3", "y = 0.5x"),
col = c(C["azul"], C["rojo"], C["verde"]), lwd = 2, bty = "n")plot(x, x^2, type = "l", col = C["azul"], lwd = 2, ylim = c(-10, 30),
xlab = "x", ylab = "y", main = "Funciones Cuadráticas: y = ax\u00b2+bx+c", font.main = 2)
lines(x, -x^2 + 10, col = C["rojo"], lwd = 2)
lines(x, 0.5*x^2 - 3, col = C["verde"], lwd = 2)
abline(h = 0, v = 0, lwd = 0.8)
legend("top", legend = c("y = x\u00b2", "y = -x\u00b2+10", "y = 0.5x\u00b2-3"),
col = c(C["azul"], C["rojo"], C["verde"]), lwd = 2, bty = "n")plot(x, x^3, type = "l", col = C["morado"], lwd = 2, ylim = c(-15, 15),
xlab = "x", ylab = "y", main = "Funciones C\u00fabicas", font.main = 2)
lines(x, x^3 - 3*x, col = C["naranja"], lwd = 2)
abline(h = 0, v = 0, lwd = 0.8)
legend("topleft", legend = c("y = x\u00b3", "y = x\u00b3-3x"),
col = c(C["morado"], C["naranja"]), lwd = 2, bty = "n")par(mfrow = c(1, 2))
plot(x, abs(x), type = "l", col = C["azul"], lwd = 2.5, main = "Valor Absoluto", font.main = 2,
xlab = "x", ylab = "y")
lines(x, abs(x-2) + 1, col = C["rojo"], lwd = 2)
abline(h = 0, v = 0, lwd = 0.8)
legend("top", legend = c("y=|x|", "y=|x-2|+1"), col = c(C["azul"], C["rojo"]), lwd = 2, bty = "n")
plot(x, floor(x), type = "s", col = C["verde"], lwd = 2, main = "Funciones Piso y Techo",
font.main = 2, xlab = "x", ylab = "y")
lines(x, ceiling(x), type = "s", col = C["naranja"], lwd = 2)
abline(h = 0, v = 0, lwd = 0.8)
legend("topleft", legend = c("piso(x)", "techo(x)"), col = c(C["verde"], C["naranja"]),
lwd = 2, bty = "n", cex = 0.85)x <- seq(-2*pi, 2*pi, length.out = 500)
par(mfrow = c(1, 3))
plot(x, sin(x), type = "l", col = C["azul"], lwd = 2, main = "y = sin(x)", font.main = 2, xlab="x", ylab="y")
abline(h=0, v=0, lwd=0.8)
plot(x, cos(x), type = "l", col = C["rojo"], lwd = 2, main = "y = cos(x)", font.main = 2, xlab="x", ylab="y")
abline(h=0, v=0, lwd=0.8)
plot(x, tan(x), type = "l", col = C["verde"], lwd = 2, ylim = c(-5,5), main = "y = tan(x)", font.main = 2, xlab="x", ylab="y")
abline(h=0, v=0, lwd=0.8)x <- seq(0, 4*pi, length.out = 500)
plot(x, sin(x), type = "l", lwd = 2, col = C["azul"], xlab = "x", ylab = "y",
main = "Transformaciones del Seno", font.main = 2)
lines(x, 2*sin(x), lwd = 2, col = C["rojo"])
lines(x, sin(2*x), lwd = 2, col = C["verde"])
lines(x, sin(x - pi/2), lwd = 2, lty = 2, col = C["naranja"])
abline(h = 0, lwd = 0.8)
legend("bottomright", legend = c("sin(x)", "2sin(x)", "sin(2x)", "sin(x-\u03c0/2)"),
col = c(C["azul"], C["rojo"], C["verde"], C["naranja"]), lwd = 2, lty = c(1,1,1,2),
bty = "n", cex = 0.85)x_pos <- seq(0.01, 5, length.out = 300)
x_full <- seq(-3, 3, length.out = 300)
par(mfrow = c(1, 2))
plot(x_full, exp(x_full), type = "l", col = C["rojo"], lwd = 2, ylim = c(0, 20),
main = "Funciones Exponenciales", font.main = 2, xlab = "x", ylab = "y")
lines(x_full, 2^x_full, col = C["azul"], lwd = 2)
lines(x_full, exp(-x_full), col = C["verde"], lwd = 2, lty = 2)
legend("topleft", legend = c("e^x", "2^x", "e^(-x)"),
col = c(C["rojo"], C["azul"], C["verde"]), lwd = 2, lty = c(1,1,2), bty = "n")
plot(x_pos, log(x_pos), type = "l", col = C["rojo"], lwd = 2, main = "Funciones Logar\u00edtmicas",
font.main = 2, xlab = "x", ylab = "y")
lines(x_pos, log2(x_pos), col = C["azul"], lwd = 2)
lines(x_pos, log10(x_pos), col = C["verde"], lwd = 2)
abline(h = 0, lwd = 0.8); abline(v = 1, lty = 3)
legend("bottomright", legend = c("ln(x)", "log2(x)", "log10(x)"),
col = c(C["rojo"], C["azul"], C["verde"]), lwd = 2, bty = "n")x <- seq(-6, 6, length.out = 300)
sigmoid <- 1 / (1 + exp(-x))
gauss <- exp(-x^2/2) / sqrt(2*pi)
par(mfrow = c(1, 2))
plot(x, sigmoid, type = "l", col = C["morado"], lwd = 2.5, xlab = "x", ylab = "y",
main = "Sigmoide: \u03c3(x) = 1/(1+e^-x)", font.main = 2)
abline(h = 0.5, col = C["gris"], lty = 3, lwd = 1.5)
plot(x, gauss, type = "l", col = C["turquesa"], lwd = 2.5, xlab = "x", ylab = "y",
main = "Gaussiana: (1/\u221a2\u03c0) e^(-x\u00b2/2)", font.main = 2)
polygon(c(x, rev(x)), c(gauss, rep(0, length(x))), col = adjustcolor(C["turquesa"], 0.2), border = NA)par(mfrow = c(3, 3))
x <- seq(-4, 4, length.out = 300)
x_pos <- seq(0.01, 4, length.out = 300)
plot(x, x, type = "l", lwd = 2.5, col = C["azul"], main = "y = x", xlab="x", ylab="y"); abline(h=0,v=0,lwd=0.5)
plot(x, x^2, type = "l", lwd = 2.5, col = C["rojo"], main = "y = x\u00b2", xlab="x", ylab="y"); abline(h=0,v=0,lwd=0.5)
plot(x, x^3, type = "l", lwd = 2.5, col = C["verde"], main = "y = x\u00b3", xlab="x", ylab="y"); abline(h=0,v=0,lwd=0.5)
plot(x_pos, sqrt(x_pos), type = "l", lwd = 2.5, col = C["naranja"], main = "y = \u221ax", xlab="x", ylab="y")
plot(x, abs(x), type = "l", lwd = 2.5, col = C["morado"], main = "y = |x|", xlab="x", ylab="y"); abline(h=0,v=0,lwd=0.5)
plot(x_pos, 1/x_pos, type = "l", lwd = 2.5, col = C["turquesa"], main = "y = 1/x", xlab="x", ylab="y", ylim=c(-10,10))
plot(x, sin(x), type = "l", lwd = 2.5, col = C["azul"], main = "y = sin(x)", xlab="x", ylab="y"); abline(h=0,v=0,lwd=0.5)
plot(x, exp(x), type = "l", lwd = 2.5, col = C["rojo"], main = "y = e^x", xlab="x", ylab="y", ylim=c(0,20))
plot(x_pos, log(x_pos), type = "l", lwd = 2.5, col = C["verde"], main = "y = ln(x)", xlab="x", ylab="y")
par(mfrow = c(1, 1))
mtext("9 Funciones Fundamentales de las Matem\u00e1ticas", side = 3, line = -1.5, outer = TRUE, font = 2, cex = 1.1)R base no tiene un modo “polar” nativo como matplotlib; se construyen convirtiendo \((r,\theta)\to(x,y)=(r\cos\theta, r\sin\theta)\) y graficando en cartesianas.
theta <- seq(0, 2*pi, length.out = 500)
par(mfrow = c(1, 3))
r1 <- 1 + cos(theta)
plot(r1*cos(theta), r1*sin(theta), type = "l", col = C["rojo"], lwd = 2, asp = 1,
xlab = "", ylab = "", main = "Cardioide\nr = 1+cos(\u03b8)", font.main = 2)
r2 <- sin(3*theta)
plot(r2*cos(theta), r2*sin(theta), type = "l", col = C["verde"], lwd = 2, asp = 1,
xlab = "", ylab = "", main = "Rosa de 3 p\u00e9talos\nr = sin(3\u03b8)", font.main = 2)
r3 <- theta
plot(r3*cos(theta), r3*sin(theta), type = "l", col = C["morado"], lwd = 2, asp = 1,
xlab = "", ylab = "", main = "Espiral\nr = \u03b8", font.main = 2)t <- seq(0, 2*pi, length.out = 500)
par(mfrow = c(1, 3))
plot(cos(t), sin(t), type = "l", col = C["azul"], lwd = 2, asp = 1,
main = "C\u00edrculo\nx=cos(t), y=sin(t)", font.main = 2, xlab = "", ylab = "")
plot(3*cos(t), 2*sin(t), type = "l", col = C["rojo"], lwd = 2, asp = 1,
main = "Elipse\nx=3cos(t), y=2sin(t)", font.main = 2, xlab = "", ylab = "")
plot(sin(3*t), sin(4*t), type = "l", col = C["morado"], lwd = 1.5, asp = 1,
main = "Lissajous\nx=sin(3t), y=sin(4t)", font.main = 2, xlab = "", ylab = "")persp()x <- seq(-3, 3, length.out = 60)
y <- seq(-3, 3, length.out = 60)
Z1 <- outer(x, y, function(x, y) sin(sqrt(x^2 + y^2)))
Z2 <- outer(x, y, function(x, y) x^2 + y^2)
Z3 <- outer(x, y, function(x, y) x^2 - y^2)
par(mfrow = c(1, 3))
persp(x, y, Z1, theta = 35, phi = 25, col = "lightblue", shade = 0.4,
main = "z = sin(\u221a(x\u00b2+y\u00b2))", ticktype = "detailed", cex.main = 0.9)
persp(x, y, Z2, theta = 35, phi = 25, col = "lightyellow", shade = 0.4,
main = "z = x\u00b2+y\u00b2", ticktype = "detailed", cex.main = 0.9)
persp(x, y, Z3, theta = 35, phi = 25, col = "lightpink", shade = 0.4,
main = "z = x\u00b2-y\u00b2", ticktype = "detailed", cex.main = 0.9)par(mfrow = c(1, 2))
image(x, y, Z1, col = hcl.colors(50, "viridis"), main = "Mapa de Calor", font.main = 2,
xlab = "x", ylab = "y")
contour(x, y, Z1, nlevels = 15, col = hcl.colors(15, "RdBu"), main = "Curvas de Nivel",
font.main = 2, xlab = "x", ylab = "y", asp = 1)tabla <- data.frame(
Concepto = c("Tipo de variable", "Crear vector", "Secuencia", "Media", "Desviación est.",
"Crear matriz", "Producto matricial", "Inversa", "Resolver Ax=b", "Graficar",
"Subplots (paneles)", "Gráfico 3D", "Gráfico polar"),
R = c("class(x)", "c(1,2,3)", "seq(0, 10, length.out=100)", "mean(datos)", "sd(datos)",
"matrix(c(1,2,3,4), nrow=2)", "A %*% B", "solve(A)", "solve(A, b)", "plot(x, y)",
"par(mfrow=c(r,c))", "persp(x, y, Z)", "plot(r*cos(theta), r*sin(theta))")
)
knitr::kable(tabla, align = "l", caption = "Tabla resumen: concepto y su equivalente en R")| Concepto | R |
|---|---|
| Tipo de variable | class(x) |
| Crear vector | c(1,2,3) |
| Secuencia | seq(0, 10, length.out=100) |
| Media | mean(datos) |
| Desviación est. | sd(datos) |
| Crear matriz | matrix(c(1,2,3,4), nrow=2) |
| Producto matricial | A %*% B |
| Inversa | solve(A) |
| Resolver Ax=b | solve(A, b) |
| Graficar | plot(x, y) |
| Subplots (paneles) | par(mfrow=c(r,c)) |
| Gráfico 3D | persp(x, y, Z) |
| Gráfico polar | plot(rcos(theta), rsin(theta)) |
class() el tipo de cada variable.Las notas de 10 estudiantes son: \(12,15,8,17,14,11,19,13,16,10\).
resumen(datos) que retorne: media,
mediana, mínimo, máximo.for + if:
Excelente (\(\ge 18\)), Bueno (\(\ge 14\)), Regular (\(\ge 11\)), Desaprobado (\(<11\)).seq().sum(a*b)).Resuelva el sistema: \[3x+2y-z=1 \qquad x-y+4z=11 \qquad 2x+3y+z=7\]
solve(A, b).Grafique en un panel 2×2:
persp().Simule el lanzamiento de un dado \(N=10\,000\) veces:
sample(1:6, 10000, replace = TRUE).Este cuaderno cubre los Fundamentos de R necesarios para Estadística:
sprintf()if/else if/else) y bucles
(for, while)\(x) ...)persp(), mapas de calor, contornos)
Documento elaborado por MSc. Jeel Cueva — Especialista
en Econometría Aplicada.
Traducción a R Markdown del notebook
original de Python, publicable en RPubs.