SECCION 1 PRIMEROS PASOS CON R
# Verificar versión de R instalada
R.version.string
## [1] "R version 4.4.1 (2024-06-14 ucrt)"
# Información completa del sistema
R.version
## _
## platform x86_64-w64-mingw32
## arch x86_64
## os mingw32
## crt ucrt
## system x86_64, mingw32
## status
## major 4
## minor 4.1
## year 2024
## month 06
## day 14
## svn rev 86737
## language R
## version.string R version 4.4.1 (2024-06-14 ucrt)
## nickname Race for Your Life
# Personalizar el prompt (recomendado para claridad en scripts educativos)
options(prompt = "R> ")
options(continue = "+ ")
# Verificar directorio actual
getwd()
## [1] "C:/Users/alumno/Desktop/OÑAR"
# Cambiar directorio
#setwd("D:/Sesion2")
# Listar archivos en el directorio
list.files()
## [1] "mi_sesion.RData" "SEMANA-2---PELE_files" "SEMANA-2--PELEE.html"
## [4] "SEMANA-2--PELEE.Rmd" "SEMANA 2- PELEE.Rmd" "SEMANA 2 - PELE.Rmd"
# Crear directorio desde R
#dir.create("nuevo_proyecto")
# Listar archivos recursivamente
list.files(recursive = TRUE)
## [1] "mi_sesion.RData"
## [2] "SEMANA-2---PELE_files/figure-html/unnamed-chunk-9-1.png"
## [3] "SEMANA-2--PELEE.html"
## [4] "SEMANA-2--PELEE.Rmd"
## [5] "SEMANA 2- PELEE.Rmd"
## [6] "SEMANA 2 - PELE.Rmd"
# Verificar versión de Python instalada
import sys
print(sys.version)
## 3.11.13 (main, Jul 11 2025, 22:36:59) [MSC v.1944 64 bit (AMD64)]
# Información completa del sistema
import platform
print(platform.platform())
## Windows-10-10.0.22621-SP0
print(f"Python {sys.version}")
## Python 3.11.13 (main, Jul 11 2025, 22:36:59) [MSC v.1944 64 bit (AMD64)]
print(f"Ejecutando en {platform.processor()}")
## Ejecutando en Intel64 Family 6 Model 165 Stepping 5, GenuineIntel
# No hay equivalente directo al prompt personalizado en scripts
# El prompt es manejado por el entorno (IDLE, Jupyter, terminal)
# Verificar directorio actual
import os
print(os.getcwd())
## C:\Users\alumno\Desktop\OÑAR
# Cambiar directorio
# os.chdir("D:/Sesion2")
# Listar archivos en el directorio
print(os.listdir())
## ['mi_sesion.RData', 'SEMANA 2 - PELE.Rmd', 'SEMANA 2- PELEE.Rmd', 'SEMANA-2---PELE_files', 'SEMANA-2--PELEE.html', 'SEMANA-2--PELEE.Rmd']
# Crear directorio desde Python
# os.makedirs("nuevo_proyecto", exist_ok=True)
# Listar archivos recursivamente
import glob
archivos = []
for root, dirs, files in os.walk("."):
for file in files:
archivos.append(os.path.join(root, file))
print(archivos)
## ['.\\mi_sesion.RData', '.\\SEMANA 2 - PELE.Rmd', '.\\SEMANA 2- PELEE.Rmd', '.\\SEMANA-2--PELEE.html', '.\\SEMANA-2--PELEE.Rmd', '.\\SEMANA-2---PELE_files\\figure-html\\unnamed-chunk-9-1.png']
# Operaciones básicas
2 + 3 # Suma
## [1] 5
14/6 # División
## [1] 2.333333
14/(6+5) # Paréntesis modifican el orden
## [1] 1.272727
3^2 # Potenciación (preferido sobre **)
## [1] 9
2**3 # Alternativa para potenciación, compatible con otros lenguajes
## [1] 8
# Operaciones básicas
2 + 3 # Suma
## 5
14 / 6 # División
## 2.3333333333333335
14 / (6 + 5) # Paréntesis modifican el orden
## 1.2727272727272727
3 ** 2 # Potenciación (Python usa **)
## 9
2 ** 3 # Potenciación
## 8
# Operaciones avanzadas
17%/%5 # Parte entera de 17/5 (división floor)
## [1] 3
# Resto y división entera
17%%5 # Resto de 17/5 (módulo)
## [1] 2
# Funciones matemáticas
sqrt(9) # Raíz cuadrada, definida como xˆ{1/2}
## [1] 3
abs(-5) # Valor absoluto
## [1] 5
# Funciones trigonométricas (en radianes)
sin(pi/2) #seno(90°=pi/2 rad)
## [1] 1
cos(0)
## [1] 1
# Logaritmos
log(10) # Logaritmo natural ln(x), base e = 2.718...
## [1] 2.302585
log10(100) # Logaritmo base 10
## [1] 2
log(8, base = 2) # log_2(8)=3
## [1] 3
# Exponencial
exp(1) # eˆ1 = 2.718
## [1] 2.718282
# Otras funciones: ceiling(x), floor(x), round(x, digits)
round(pi, digits = 4)
## [1] 3.1416
#Operaciones avanzadas
import math
# División floor (parte entera)
17 // 5 # Equivalente a 17%/%5 en R
## 3
# Resto (módulo)
17 % 5 # Equivalente a 17%%5 en R
## 2
# Funciones matemáticas
math.sqrt(9) # Raíz cuadrada
## 3.0
abs(-5) # Valor absoluto
## 5
# Funciones trigonométricas (en radianes)
math.sin(math.pi / 2) # seno(90°=pi/2 rad)
## 1.0
math.cos(0)
## 1.0
# Logaritmos
math.log(10) # Logaritmo natural ln(x), base e
## 2.302585092994046
math.log10(100) # Logaritmo base 10
## 2.0
math.log(8, 2) # log_2(8)=3
## 3.0
# Exponencial
math.exp(1) # e^1 = 2.718
## 2.718281828459045
# Otras funciones
math.ceil(4.3) # ceiling
## 5
math.floor(4.7) # floor
## 4
round(math.pi, 4) # redondeo
## 3.1416
#Notacion cientifica (E- notation)
# Forzar notación científica
format(12345, scientific = TRUE)
## [1] "1.2345e+04"
# Suprimir notación científica
options(scipen = 999)
0.0000002533
## [1] 0.0000002533
# Restaurar default
options(scipen = 0)
# Notación científica
print("{:e}".format(12345)) # Forzar notación científica
## 1.234500e+04
# Python generalmente muestra números pequeños sin notación científica
print(0.0000002533)
## 2.533e-07
# Formateo personalizado
print("{:.10f}".format(0.0000002533)) # Mostrar con 10 decimales
## 0.0000002533
#Sistema de ayuda
# Ayuda sobre funciones específicas
?mean
## starting httpd help server ... done
help(mean)
# Buscar en toda la documentación
??mean
help.search("mean")
# Ayuda sobre operadores (necesita comillas)
?"+"
help("+")
# Ver ejemplos
example(mean)
##
## meanR> x <- c(0:10, 50)
##
## meanR> xm <- mean(x)
##
## meanR> c(xm, mean(x, trim = 0.10))
## [1] 8.75 5.50
# Obtener argumentos de una función
args(mean)
## function (x, ...)
## NULL
# function (x, ...)
# Ver código fuente de una función (para funciones no primitivas)
mean
## function (x, ...)
## UseMethod("mean")
## <bytecode: 0x000001da4171c6f8>
## <environment: namespace:base>
# Búsqueda aprox. con apropos
apropos("mean")
## [1] ".colMeans" ".rowMeans" "colMeans" "kmeans"
## [5] "mean" "mean.Date" "mean.default" "mean.difftime"
## [9] "mean.POSIXct" "mean.POSIXlt" "rowMeans" "weighted.mean"
# Ayuda en paquetes instalados
??ggplot
# Ayuda sobre funciones específicas
help(sum) # Equivalente a ?mean o help(mean)
## Help on built-in function sum in module builtins:
##
## sum(iterable, /, start=0)
## Return the sum of a 'start' value (default: 0) plus an iterable of numbers
##
## When the iterable is empty, return the start value.
## This function is intended specifically for use with numeric values and may
## reject non-numeric types.
# help() abre el sistema interactivo de ayuda
# Buscar en documentación - no hay equivalente directo a ??
# Se puede usar help() interactivo o documentación online
# Ayuda sobre operadores
help("+") # Algunos operadores pueden necesitar comillas
## Operator precedence
## *******************
##
## The following table summarizes the operator precedence in Python, from
## highest precedence (most binding) to lowest precedence (least
## binding). Operators in the same box have the same precedence. Unless
## the syntax is explicitly given, operators are binary. Operators in
## the same box group left to right (except for exponentiation and
## conditional expressions, which group from right to left).
##
## Note that comparisons, membership tests, and identity tests, all have
## the same precedence and have a left-to-right chaining feature as
## described in the Comparisons section.
##
## +-------------------------------------------------+---------------------------------------+
## | Operator | Description |
## |=================================================|=======================================|
## | "(expressions...)", "[expressions...]", "{key: | Binding or parenthesized expression, |
## | value...}", "{expressions...}" | list display, dictionary display, set |
## | | display |
## +-------------------------------------------------+---------------------------------------+
## | "x[index]", "x[index:index]", | Subscription, slicing, call, |
## | "x(arguments...)", "x.attribute" | attribute reference |
## +-------------------------------------------------+---------------------------------------+
## | "await x" | Await expression |
## +-------------------------------------------------+---------------------------------------+
## | "**" | Exponentiation [5] |
## +-------------------------------------------------+---------------------------------------+
## | "+x", "-x", "~x" | Positive, negative, bitwise NOT |
## +-------------------------------------------------+---------------------------------------+
## | "*", "@", "/", "//", "%" | Multiplication, matrix |
## | | multiplication, division, floor |
## | | division, remainder [6] |
## +-------------------------------------------------+---------------------------------------+
## | "+", "-" | Addition and subtraction |
## +-------------------------------------------------+---------------------------------------+
## | "<<", ">>" | Shifts |
## +-------------------------------------------------+---------------------------------------+
## | "&" | Bitwise AND |
## +-------------------------------------------------+---------------------------------------+
## | "^" | Bitwise XOR |
## +-------------------------------------------------+---------------------------------------+
## | "|" | Bitwise OR |
## +-------------------------------------------------+---------------------------------------+
## | "in", "not in", "is", "is not", "<", "<=", ">", | Comparisons, including membership |
## | ">=", "!=", "==" | tests and identity tests |
## +-------------------------------------------------+---------------------------------------+
## | "not x" | Boolean NOT |
## +-------------------------------------------------+---------------------------------------+
## | "and" | Boolean AND |
## +-------------------------------------------------+---------------------------------------+
## | "or" | Boolean OR |
## +-------------------------------------------------+---------------------------------------+
## | "if" – "else" | Conditional expression |
## +-------------------------------------------------+---------------------------------------+
## | "lambda" | Lambda expression |
## +-------------------------------------------------+---------------------------------------+
## | ":=" | Assignment expression |
## +-------------------------------------------------+---------------------------------------+
##
## -[ Footnotes ]-
##
## [1] While "abs(x%y) < abs(y)" is true mathematically, for floats it
## may not be true numerically due to roundoff. For example, and
## assuming a platform on which a Python float is an IEEE 754 double-
## precision number, in order that "-1e-100 % 1e100" have the same
## sign as "1e100", the computed result is "-1e-100 + 1e100", which
## is numerically exactly equal to "1e100". The function
## "math.fmod()" returns a result whose sign matches the sign of the
## first argument instead, and so returns "-1e-100" in this case.
## Which approach is more appropriate depends on the application.
##
## [2] If x is very close to an exact integer multiple of y, it’s
## possible for "x//y" to be one larger than "(x-x%y)//y" due to
## rounding. In such cases, Python returns the latter result, in
## order to preserve that "divmod(x,y)[0] * y + x % y" be very close
## to "x".
##
## [3] The Unicode standard distinguishes between *code points* (e.g.
## U+0041) and *abstract characters* (e.g. “LATIN CAPITAL LETTER A”).
## While most abstract characters in Unicode are only represented
## using one code point, there is a number of abstract characters
## that can in addition be represented using a sequence of more than
## one code point. For example, the abstract character “LATIN
## CAPITAL LETTER C WITH CEDILLA” can be represented as a single
## *precomposed character* at code position U+00C7, or as a sequence
## of a *base character* at code position U+0043 (LATIN CAPITAL
## LETTER C), followed by a *combining character* at code position
## U+0327 (COMBINING CEDILLA).
##
## The comparison operators on strings compare at the level of
## Unicode code points. This may be counter-intuitive to humans. For
## example, ""\u00C7" == "\u0043\u0327"" is "False", even though both
## strings represent the same abstract character “LATIN CAPITAL
## LETTER C WITH CEDILLA”.
##
## To compare strings at the level of abstract characters (that is,
## in a way intuitive to humans), use "unicodedata.normalize()".
##
## [4] Due to automatic garbage-collection, free lists, and the dynamic
## nature of descriptors, you may notice seemingly unusual behaviour
## in certain uses of the "is" operator, like those involving
## comparisons between instance methods, or constants. Check their
## documentation for more info.
##
## [5] The power operator "**" binds less tightly than an arithmetic or
## bitwise unary operator on its right, that is, "2**-1" is "0.5".
##
## [6] The "%" operator is also used for string formatting; the same
## precedence applies.
##
## Related help topics: lambda, or, and, not, in, is, BOOLEAN, COMPARISON,
## BITWISE, SHIFTING, BINARY, FORMATTING, POWER, UNARY, ATTRIBUTES,
## SUBSCRIPTS, SLICINGS, CALLS, TUPLES, LISTS, DICTIONARIES
# Ver ejemplos - generalmente en la documentación de help()
# o se pueden buscar ejemplos online
# Obtener argumentos de una función
import inspect
print(inspect.signature(sum))
## (iterable, /, start=0)
# Ver código fuente (para funciones no built-in)
import numpy as np # Ejemplo con función de numpy
print(np.mean.__doc__) # Documentación
##
## Compute the arithmetic mean along the specified axis.
##
## Returns the average of the array elements. The average is taken over
## the flattened array by default, otherwise over the specified axis.
## `float64` intermediate and return values are used for integer inputs.
##
## Parameters
## ----------
## a : array_like
## Array containing numbers whose mean is desired. If `a` is not an
## array, a conversion is attempted.
## axis : None or int or tuple of ints, optional
## Axis or axes along which the means are computed. The default is to
## compute the mean of the flattened array.
##
## If this is a tuple of ints, a mean is performed over multiple axes,
## instead of a single axis or all the axes as before.
## dtype : data-type, optional
## Type to use in computing the mean. For integer inputs, the default
## is `float64`; for floating point inputs, it is the same as the
## input dtype.
## out : ndarray, optional
## Alternate output array in which to place the result. The default
## is ``None``; if provided, it must have the same shape as the
## expected output, but the type will be cast if necessary.
## See :ref:`ufuncs-output-type` for more details.
## See :ref:`ufuncs-output-type` for more details.
##
## keepdims : bool, optional
## If this is set to True, the axes which are reduced are left
## in the result as dimensions with size one. With this option,
## the result will broadcast correctly against the input array.
##
## If the default value is passed, then `keepdims` will not be
## passed through to the `mean` method of sub-classes of
## `ndarray`, however any non-default value will be. If the
## sub-class' method does not implement `keepdims` any
## exceptions will be raised.
##
## where : array_like of bool, optional
## Elements to include in the mean. See `~numpy.ufunc.reduce` for details.
##
## .. versionadded:: 1.20.0
##
## Returns
## -------
## m : ndarray, see dtype parameter above
## If `out=None`, returns a new array containing the mean values,
## otherwise a reference to the output array is returned.
##
## See Also
## --------
## average : Weighted average
## std, var, nanmean, nanstd, nanvar
##
## Notes
## -----
## The arithmetic mean is the sum of the elements along the axis divided
## by the number of elements.
##
## Note that for floating-point input, the mean is computed using the
## same precision the input has. Depending on the input data, this can
## cause the results to be inaccurate, especially for `float32` (see
## example below). Specifying a higher-precision accumulator using the
## `dtype` keyword can alleviate this issue.
##
## By default, `float16` results are computed using `float32` intermediates
## for extra precision.
##
## Examples
## --------
## >>> import numpy as np
## >>> a = np.array([[1, 2], [3, 4]])
## >>> np.mean(a)
## 2.5
## >>> np.mean(a, axis=0)
## array([2., 3.])
## >>> np.mean(a, axis=1)
## array([1.5, 3.5])
##
## In single precision, `mean` can be inaccurate:
##
## >>> a = np.zeros((2, 512*512), dtype=np.float32)
## >>> a[0, :] = 1.0
## >>> a[1, :] = 0.1
## >>> np.mean(a)
## np.float32(0.54999924)
##
## Computing the mean in float64 is more accurate:
##
## >>> np.mean(a, dtype=np.float64)
## 0.55000000074505806 # may vary
##
## Computing the mean in timedelta64 is available:
##
## >>> b = np.array([1, 3], dtype="timedelta64[D]")
## >>> np.mean(b)
## np.timedelta64(2,'D')
##
## Specifying a where argument:
##
## >>> a = np.array([[5, 9, 13], [14, 10, 12], [11, 15, 19]])
## >>> np.mean(a)
## 12.0
## >>> np.mean(a, where=[[True], [False], [False]])
## 9.0
##
##
# inspect.getsource(np.mean) # Código fuente (si disponible)
# Búsqueda aproximada - no hay equivalente directo a apropos
# Se puede usar dir() para ver objetos disponibles
SECCION 2 NUMERICS, ARITMETICA Y ASIGNACION
#Asignacion de objetos
# Método tradicional: flecha hacia la izquierda (estándar en comunidad R)
x <- 5
x
## [1] 5
# Método alternativo: signo igual (reservar para argumentos de función para evitar confusión)
y = 10
y
## [1] 10
# Asignación hacia la derecha (poco común, pero útil en pipelines)
15 -> z
z
## [1] 15
# Mostrar valor al asignar (usar paréntesis para evaluación inmediata)
(resultado <- 2 + 3)
## [1] 5
# Asignación en entornos (avanzado)
assign("var_global", 100, envir = .GlobalEnv)
var_global
## [1] 100
Reglas para nombrar objetos:
Reglas obligatorias: -Deben comenzar con una letra (a-z, A-Z) o punto (.). -Pueden contener letras, números, puntos (.) y guiones bajos (_). -No pueden contener espacios ni caracteres especiales como @, #, $, etc. -Máxima longitud: No hay límite práctico, pero mantén corto para legibilidad.
Mejores prácticas: -Usar nombres descriptivos: edad_promedio en lugar de x para claridad. -Consistencia en estilo: snake_case (recomendado por tidyverse) o camelCase. -Evitar nombres de funciones existentes: mean, sum, data. Usa ls(all.names = TRUE) para -verificar conflictos. -Convenciones: Usa . para objetos temporales o internos (e.g., .temp_var).
mi_variable <- 10
Variable2 <- 20
datos.2023 <- 30
.variable_oculta <- 40 # Empieza con punto (convención para variables "privadas" o hidden)
# Nombres inválidos (producen error)
# 2variable <- 10 # No puede empezar con número
# mi-variable <- 10 # No puede contener guión medio (usa _ en su lugar)
# mi variable <- 10 # No puede contener espacios (usa _ o .)
mi_variable = 10
Variable2 = 20
datos_2023 = 30 # Python prefiere snake_case sobre dot notation
_variable_oculta = 40 # Convención para variables "protegidas" o internas
# Nombres inválidos (producen error)
# 2variable = 10 # No puede empezar con número
# mi-variable = 10 # No puede contener guión medio (usa _ en su lugar)
# mi variable = 10 # No puede contener espacios (usa _)
# Python permite pero no recomienda variables que empiecen con _
# (es una convención para indicar que son "protegidas")
# Estas palabras están reservadas para sintaxis interna y no deben usarse como nombres.
# TRUE, FALSE, NULL, Inf, NaN, NA
# if, else, repeat, while, function, for, in, next, break
# Ver todas las palabras reservadas
?Reserved
# Ejemplo de error
# if <- 10 # Error: unexpected assignment in "if <-"
# Estas palabras están reservadas para sintaxis interna y no pueden usarse como nombres
import keyword
# Ver todas las palabras reservadas de Python
print(keyword.kwlist)
## ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
# ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await',
# 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except',
# 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
# 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try',
# 'while', 'with', 'yield']
# Valores especiales reservados (no son keywords pero tienen significado especial)
# True, False, None
# Ejemplo de error
# if = 10 # SyntaxError: invalid syntax
# También están reservados los nombres de funciones built-in
# como: sum, len, print, input, etc. (aunque técnicamente se pueden redefinir, no es recomendable)
# Gestion del Workspace
# Ver objetos con patrón específico
ls(pattern = "var")
## [1] "mi_variable" "var_global"
# Obtener información sobre un objeto
str(x)
## num 5
# Eliminar objetos específicos
rm(x, y)
# Eliminar todos los objetos
rm(list = ls())
# Guardar workspace
save.image("mi_sesion.RData")
# Cargar workspace
#load("mi_sesion.RData")
# Guardar objetos específicos
#save(mi_variable, file = "datos.RData")
# Tamaño de objetos
#object.size(mi_variable)
# Entornos avanzados: Usa new.env() para workspaces aislados
env <- new.env()
env$var <- 10
ls(env)
## [1] "var"
#Tipos de datos atómicos
#NUMERIC (Double)
#Por defecto, R trata todos los números como numeric (double precision, IEEE 754).
x <- 5
class(x)
## [1] "numeric"
typeof(x)
## [1] "double"
# Límites numéricos del sistema
.Machine$double.eps # Epsilon de máquina, precisión mínima
## [1] 2.220446e-16
#INTEGER
#Los enteros requieren especificación explícita para optimizar memoria en grandes datasets.
y <- 10L
class(y)
## [1] "integer"
# Las secuencias son enteros por defecto
z <- 1:5
class(z)
## [1] "integer"
# Coerción explícita
w <- as.integer(3.7)
w
## [1] 3
# Límites de enteros
.Machine$integer.max
## [1] 2147483647
#CHARACTER
#Cadenas de texto, inmutables y vectorizables.
# Crear cadenas (comillas dobles o simples, equivalentes)
nombre <- "Juan"
apellido <- 'Pérez'
class(nombre)
## [1] "character"
# Longitud de cadena
nchar(nombre)
## [1] 4
# Cadenas vacías
vacia <- ""
nchar(vacia)
## [1] 0
# Manipulación: paste, substr, gsub
paste(nombre, apellido)
## [1] "Juan Pérez"
substr(nombre, 1, 2)
## [1] "Ju"
#LOGICAL
#Valores booleanos, útiles para máscaras y condiciones.
# Valores lógicos
verdadero <- TRUE
falso <- FALSE
# Abreviaciones (usar con precaución, preferir completo para claridad)
v <- T
f <- F
class(verdadero)
## [1] "logical"
# Coerción automática en contexto numérico (TRUE=1, FALSE=0)
TRUE + FALSE
## [1] 1
sum(c(TRUE, TRUE, FALSE))
## [1] 2
# NUMERIC (Float - equivalente a double en R)
x = 5.0
print(type(x)) # <class 'float'>
## <class 'float'>
# Precisión del sistema
import sys
print(sys.float_info.epsilon) # Épsilon de máquina, precisión mínima
## 2.220446049250313e-16
# Información completa de floats
print(sys.float_info)
## sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)
# INTEGER
y = 10
print(type(y)) # <class 'int'> (Python 3+)
## <class 'int'>
# Los enteros en Python tienen precisión arbitraria (no hay límite como en R)
# Pero podemos ver el límite de enteros de 64 bits
import numpy as np
print(np.iinfo(np.int64).max) # 9223372036854775807
## 9223372036854775807
# Coerción explícita
w = int(3.7)
print(w) # 3 (trunca, no redondea)
## 3
# Secuencias (rango) - son enteros
z = list(range(1, 6))
print(z) # [1, 2, 3, 4, 5]
## [1, 2, 3, 4, 5]
print(type(z[0])) # <class 'int'>
## <class 'int'>
# CHARACTER (Strings)
nombre = "Juan"
apellido = 'Pérez' # Comillas simples o dobles, equivalentes
print(type(nombre)) # <class 'str'>
## <class 'str'>
# Longitud de cadena
print(len(nombre)) # 4
## 4
# Cadenas vacías
vacia = ""
print(len(vacia)) # 0
## 0
# Manipulación de strings
# Concatenación (equivalente a paste)
print(nombre + " " + apellido) # Juan Pérez
## Juan Pérez
print(f"{nombre} {apellido}") # Juan Pérez (f-strings, recomendado)
## Juan Pérez
# Substrings (equivalente a substr)
print(nombre[0:2]) # Ju (slicing)
## Ju
# Reemplazo (equivalente a gsub)
texto = "Hola mundo"
print(texto.replace("mundo", "Python")) # Hola Python
## Hola Python
# LOGICAL (Boolean)
verdadero = True
falso = False
print(type(verdadero)) # <class 'bool'>
## <class 'bool'>
# NO usar abreviaciones como en R (T/F), Python requiere True/False completo
# v = T # Error - T no está definido
# f = F # Error - F no está definido
# Coerción automática en contexto numérico (True=1, False=0)
print(True + False) # 1
## 1
print(True * 5) # 5
## 5
print(False * 10) # 0
## 0
# Suma de booleanos
valores = [True, True, False]
print(sum(valores)) # 2
## 2
# Conversiones explícitas
numero = 42
print(float(numero)) # 42.0
## 42.0
print(str(numero)) # "42"
## 42
print(bool(numero)) # True (0 → False, cualquier otro → True)
## True
# Conversiones con numpy
import numpy as np
arr = np.array([1, 2, 3])
print(arr.astype(float)) # [1. 2. 3.]
## [1. 2. 3.]
print(arr.astype(str)) # ['1' '2' '3']
## ['1' '2' '3']
print(arr.astype(bool)) # [True True True]
## [ True True True]
# Conversiones explícitas
numero = 42
print(float(numero)) # 42.0
## 42.0
print(str(numero)) # "42"
## 42
print(bool(numero)) # True (0 → False, cualquier otro → True)
## True
# Conversiones con numpy
import numpy as np
arr = np.array([1, 2, 3])
print(arr.astype(float)) # [1. 2. 3.]
## [1. 2. 3.]
print(arr.astype(str)) # ['1' '2' '3']
## ['1' '2' '3']
print(arr.astype(bool)) # [True True True]
## [ True True True]
#COMPLEX
#Para matemáticas complejas, como en ingeniería o física.
# Números complejos
z1 <- 3 + 4i
z2 <- complex(real = 2, imaginary = -1)
class(z1)
## [1] "complex"
# Operaciones con complejos
Re(z1) # Parte real
## [1] 3
Im(z1) # Parte imaginaria
## [1] 4
Mod(z1) # Módulo |z| = sqrt(Reˆ2 + Imˆ2)
## [1] 5
Arg(z1) # Argumento (ángulo en radianes)
## [1] 0.9272952
Conj(z1) # Conjugado
## [1] 3-4i
# Multiplicación: (a+bi)(c+di) = (ac-bd) + (ad+bc)i
z1 * z2
## [1] 10+5i
# Números complejos (equivalente a 3 + 4i)
z1 = 3 + 4j # Nota: usar 'j' en lugar de 'i' en Python
print(z1) # (3+4j)
## (3+4j)
# Otra forma de crear (equivalente a complex(real=2, imaginary=-1))
z2 = complex(2, -1)
print(z2) # (2-1j)
## (2-1j)
# Verificar el tipo
print(type(z1)) # <class 'complex'>
## <class 'complex'>
import cmath # Módulo para funciones matemáticas complejas
import math
# Parte real (equivalente a Re(z1))
print(z1.real) # 3.0
## 3.0
# Parte imaginaria (equivalente a Im(z1))
print(z1.imag) # 4.0
## 4.0
# Módulo |z| = sqrt(Re² + Im²) (equivalente a Mod(z1))
print(abs(z1)) # 5.0
## 5.0
# o usando cmath
print(cmath.polar(z1)[0]) # 5.0
## 5.0
# Argumento (ángulo en radianes) (equivalente a Arg(z1))
print(cmath.phase(z1)) # 0.9272952180016122 radianes
## 0.9272952180016122
# También se puede obtener con polar()
print(cmath.polar(z1)[1]) # 0.9272952180016122
## 0.9272952180016122
# Conjugado (equivalente a Conj(z1))
print(z1.conjugate()) # (3-4j)
## (3-4j)
SECCION 3 - VECTORES En R, un vector es una secuencia de elementos del mismo tipo de datos. Incluso un valor único es técnicamente un vector de longitud 1. Los vectores son la estructura de datos fundamental sobre la cual se construyen todas las demás estructuras en R, como matrices, data frames y listas. Matemáticamente, un vector en R corresponde a un array 1D homogéneo. Características clave: -Homogéneos (mismo tipo de datos): Si mezclas tipos, R coerce al tipo más general (e.g., numeric + character = character). -Indexados (base 1): El primer elemento es [1], no [0] como en Python o C. -Dinámicos (pueden crecer o reducirse): Pero reasignar crea copias, lo que puede ser ineficiente en bucles (prealoca con vector()). -Vectorizados (operaciones aplicadas a todos los elementos): Esto evita bucles, mejorando velocidad y legibilidad. -Atributos: Pueden tener nombres, dimensiones, clases adicionales.
#CREACION DE VECTORES
# Vectores numéricos
numeros <- c(1, 3, 5, 7, 9)
numeros
## [1] 1 3 5 7 9
# Vectores de caracteres
colores <- c("rojo", "verde", "azul")
colores
## [1] "rojo" "verde" "azul"
# Vectores lógicos
respuestas <- c(TRUE, FALSE, TRUE, FALSE)
# Combinar cálculos
calculos <- c(2+3, sqrt(16), 10/2)
calculos
## [1] 5 4 5
# Combinar vectores existentes
v1 <- c(1, 2)
v2 <- c(3, 4)
v_combinado <- c(v1, v2)
v_combinado
## [1] 1 2 3 4
# Coerción implícita
mix <- c(1, "dos", TRUE)
class(mix)
## [1] "character"
# Vectores numéricos (equivalente a c(1, 3, 5, 7, 9))
import numpy as np
# Con listas de Python
numeros_lista = [1, 3, 5, 7, 9]
print(numeros_lista) # [1, 3, 5, 7, 9]
## [1, 3, 5, 7, 9]
# Con numpy arrays (recomendado para análisis numérico)
numeros_array = np.array([1, 3, 5, 7, 9])
print(numeros_array) # [1 3 5 7 9]
## [1 3 5 7 9]
# Vectores de caracteres (c("rojo", "verde", "azul"))
colores_lista = ["rojo", "verde", "azul"]
print(colores_lista) # ['rojo', 'verde', 'azul']
## ['rojo', 'verde', 'azul']
colores_array = np.array(["rojo", "verde", "azul"])
print(colores_array) # ['rojo' 'verde' 'azul']
## ['rojo' 'verde' 'azul']
# Vectores lógicos (c(TRUE, FALSE, TRUE, FALSE))
respuestas_lista = [True, False, True, False]
print(respuestas_lista) # [True, False, True, False]
## [True, False, True, False]
respuestas_array = np.array([True, False, True, False])
print(respuestas_array) # [ True False True False]
## [ True False True False]
#OPERADOR PARA SECUENCIAS
# Secuencias enteras ascendentes
1:10
## [1] 1 2 3 4 5 6 7 8 9 10
# Secuencias descendentes
10:1
## [1] 10 9 8 7 6 5 4 3 2 1
# Con números negativos
-3:3
## [1] -3 -2 -1 0 1 2 3
# Usando variables
inicio <- 5
fin <- 8
inicio:fin
## [1] 5 6 7 8
# Con fracciones (coerce a integer si posible)
1.5:5.5 # 1 2 3 4 5 (trunca)
## [1] 1.5 2.5 3.5 4.5 5.5
# Secuencias enteras ascendentes (1:10 en R)
secuencia = list(range(1, 11))
print(secuencia) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
## [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# O con numpy (mejor para análisis numérico)
import numpy as np
secuencia = np.arange(1, 11)
print(secuencia) # [ 1 2 3 4 5 6 7 8 9 10]
## [ 1 2 3 4 5 6 7 8 9 10]
# Secuencias descendentes (10:1 en R)
secuencia = list(range(10, 0, -1))
print(secuencia) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
## [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
# Con numpy
secuencia = np.arange(10, 0, -1)
print(secuencia) # [10 9 8 7 6 5 4 3 2 1]
## [10 9 8 7 6 5 4 3 2 1]
# Con números negativos (-3:3 en R)
secuencia = list(range(-3, 4))
print(secuencia) # [-3, -2, -1, 0, 1, 2, 3]
## [-3, -2, -1, 0, 1, 2, 3]
# Con numpy
secuencia = np.arange(-3, 4)
print(secuencia) # [-3 -2 -1 0 1 2 3]
## [-3 -2 -1 0 1 2 3]
#FUNCION seq() PARA SECUENCIAS FLEXIBLES
# Por incremento específico
seq(from = 0, to = 1, by = 0.2)
## [1] 0.0 0.2 0.4 0.6 0.8 1.0
# Por número de elementos
seq(from = 0, to = 1, length.out = 6)
## [1] 0.0 0.2 0.4 0.6 0.8 1.0
# Forma abreviada cuando se usan los primeros argumentos
seq(0, 1, 0.25)
## [1] 0.00 0.25 0.50 0.75 1.00
import numpy as np
# Por incremento específico (seq(from=0, to=1, by=0.2))
secuencia = np.arange(0, 1.1, 0.2) # 1.1 para incluir el último valor
print(secuencia) # [0. 0.2 0.4 0.6 0.8 1. ]
## [0. 0.2 0.4 0.6 0.8 1. ]
# Por número de elementos (seq(from=0, to=1, length.out=6))
secuencia = np.linspace(0, 1, 6)
print(secuencia) # [0. 0.2 0.4 0.6 0.8 1. ]
## [0. 0.2 0.4 0.6 0.8 1. ]
# Forma abreviada (seq(0, 1, 0.25))
secuencia = np.arange(0, 1.1, 0.25) # 1.1 para incluir el 1.0
print(secuencia) # [0. 0.25 0.5 0.75 1. ]
## [0. 0.25 0.5 0.75 1. ]
#FECHAS
# Secuencias de fechas (ejemplo , requiere as.Date)
seq(from = as.Date("2023-01-01"), to = as.Date("2023-01-10"), by = "day")
## [1] "2023-01-01" "2023-01-02" "2023-01-03" "2023-01-04" "2023-01-05"
## [6] "2023-01-06" "2023-01-07" "2023-01-08" "2023-01-09" "2023-01-10"
# Por meses
seq(as.Date("2023-01-01"), by = "month", length.out = 4)
## [1] "2023-01-01" "2023-02-01" "2023-03-01" "2023-04-01"
#FUNCION rep() PARA REPETICION
# Repetir un valor
rep(5, times = 4)
## [1] 5 5 5 5
# Repetir un vector completo
rep(c(1, 2), times = 3)
## [1] 1 2 1 2 1 2
# Repetir cada elemento individualmente
rep(c(1, 2, 3), each = 2)
## [1] 1 1 2 2 3 3
import numpy as np
# Repetir un valor (rep(5, times = 4))
resultado = np.repeat(5, 4)
print(resultado) # [5 5 5 5]
## [5 5 5 5]
# Repetir un vector completo (rep(c(1, 2), times = 3))
vector = np.array([1, 2])
resultado = np.tile(vector, 3)
print(resultado) # [1 2 1 2 1 2]
## [1 2 1 2 1 2]
# Repetir cada elemento individualmente (rep(c(1, 2, 3), each = 2))
vector = np.array([1, 2, 3])
resultado = np.repeat(vector, 2)
print(resultado) # [1 1 2 2 3 3]
## [1 1 2 2 3 3]
#OTRAS FUNCIONES UTILES PARA CREAR VECTORES
# Vector de ceros
numeric(5)
## [1] 0 0 0 0 0
# Vector de cadenas vacías
character(3)
## [1] "" "" ""
# Vector lógico inicializado en FALSE
logical(4)
## [1] FALSE FALSE FALSE FALSE
# Muestreo aleatorio
set.seed(123) # Para reproducibilidad
sample(1:10, 5) # 5 números sin reemplazo
## [1] 3 10 2 8 6
sample(c("cara", "cruz"), 10, replace = TRUE) # Con reemplazo
## [1] "cara" "cara" "cruz" "cruz" "cruz" "cara" "cruz" "cara" "cruz" "cara"
# Distribución uniforme
runif(5, min = 0, max = 1)
## [1] 0.3279207 0.9545036 0.8895393 0.6928034 0.6405068
# Normal
rnorm(5, mean = 0, sd = 1)
## [1] 2.5283366 0.5490967 0.2382129 -1.0488931 1.2947633
import numpy as np
# Vector de ceros
ceros = np.zeros(5)
print(ceros) # [0. 0. 0. 0. 0.]
## [0. 0. 0. 0. 0.]
# Vector de ceros (enteros)
ceros_enteros = np.zeros(5, dtype=int)
print(ceros_enteros) # [0 0 0 0 0]
## [0 0 0 0 0]
# Vector de cadenas vacías
cadenas_vacias = np.empty(3, dtype=str)
print(cadenas_vacias) # ['' '' '']
## ['' '' '']
# O con listas de Python
cadenas_vacias_lista = [''] * 3
print(cadenas_vacias_lista) # ['', '', '']
## ['', '', '']
# Vector lógico inicializado en False
falsos = np.full(4, False)
print(falsos) # [False False False False]
## [False False False False]
# O también
falsos = np.zeros(4, dtype=bool)
print(falsos) # [False False False False]
## [False False False False]
#PROPIEDADES DE VECTORES
mi_vector <- c(10, 20, 30, 40, 50)
# Longitud
length(mi_vector)
## [1] 5
# Clase (tipo de alto nivel)
class(mi_vector)
## [1] "numeric"
# Tipo (tipo interno)
typeof(mi_vector)
## [1] "double"
mi_lista = [10, 20, 30, 40, 50]
# Longitud (equivalente a length())
print(len(mi_lista)) # 5
## 5
# Tipo (equivalente a class() - tipo del contenedor)
print(type(mi_lista)) # <class 'list'>
## <class 'list'>
# Tipo de elementos (similar a typeof() pero para cada elemento)
print([type(x) for x in mi_lista]) # [<class 'int'>, <class 'int'>, ...]
## [<class 'int'>, <class 'int'>, <class 'int'>, <class 'int'>, <class 'int'>]
# Verificar tipo uniforme (las listas pueden tener tipos mixtos)
print(all(isinstance(x, int) for x in mi_lista)) # True
## True
#VECTORES NOMBRADOS
#Permiten acceso asociativo, como diccionarios simples.
# Asignar nombres al crear
edades <- c(juan = 25, maria = 30, pedro = 28)
edades
## juan maria pedro
## 25 30 28
# Asignar nombres después de crear
alturas <- c(1.75, 1.68, 1.82)
names(alturas) <- c("juan", "maria", "pedro")
alturas
## juan maria pedro
## 1.75 1.68 1.82
# Asignar nombres al crear (equivalente más directo)
edades = {"juan": 25, "maria": 30, "pedro": 28}
print(edades) # {'juan': 25, 'maria': 30, 'pedro': 28}
## {'juan': 25, 'maria': 30, 'pedro': 28}
# Asignar nombres después de crear
alturas = [1.75, 1.68, 1.82]
nombres = ["juan", "maria", "pedro"]
alturas_con_nombres = dict(zip(nombres, alturas))
print(alturas_con_nombres) # {'juan': 1.75, 'maria': 1.68, 'pedro': 1.82}
## {'juan': 1.75, 'maria': 1.68, 'pedro': 1.82}
#INDEXACION Y SUBTESSTING
#La indexación en R es muy flexible y potente. Se puede hacer por posición, nombres, o condiciones lógicas. Recuerda que subsetting devuelve un vector, preservando atributos si posible.
#Indexación por Posición (Base 1)
letras <- c("a", "b", "c", "d", "e", "f")
# Elementos individuales
letras[1] # Primer elemento
## [1] "a"
letras[6] # Sexto elemento
## [1] "f"
# Rangos
letras[2:4]
## [1] "b" "c" "d"
letras[c(1:3, 5:6)]
## [1] "a" "b" "c" "e" "f"
# Orden alterado
letras[c(3, 1, 5, 2)]
## [1] "c" "a" "e" "b"
# Repetir índices
letras[c(1, 1, 2, 2, 3, 3)]
## [1] "a" "a" "b" "b" "c" "c"
# Índice 0 o fuera de rango
letras[0] # Vector vacío
## character(0)
letras[7] # NA
## [1] NA
#INDEXACION NEGATIVA (POR EXCLUSION)
# Excluir elementos específicos
letras[-1] # Todo excepto el primero
## [1] "b" "c" "d" "e" "f"
letras[-6] # Todo excepto el último
## [1] "a" "b" "c" "d" "e"
# Excluir múltiples elementos
letras[-c(1, 3, 5)]
## [1] "b" "d" "f"
letras[-(1:3)] # Excluir los primeros tres
## [1] "d" "e" "f"
# No se pueden mezclar índices positivos y negativos
# letras[c(1, -2)] # Error: cannot mix positive and negative indices
letras = ["a", "b", "c", "d", "e", "f"]
# Elementos individuales (¡Python usa base 0!)
print(letras[0]) # Primer elemento: 'a'
## a
print(letras[5]) # Sexto elemento: 'f'
## f
# Rangos (slicing) - [inicio:fin] donde fin no está incluido
print(letras[1:4]) # ['b', 'c', 'd'] (posiciones 1, 2, 3)
## ['b', 'c', 'd']
# Múltiples rangos (necesitamos concatenar)
print(letras[0:3] + letras[4:6]) # ['a', 'b', 'c', 'e', 'f']
## ['a', 'b', 'c', 'e', 'f']
# Orden alterado (usando list comprehension)
indices = [2, 0, 4, 1]
print([letras[i] for i in indices]) # ['c', 'a', 'e', 'b']
## ['c', 'a', 'e', 'b']
# Repetir índices
indices_repetidos = [0, 0, 1, 1, 2, 2]
print([letras[i] for i in indices_repetidos]) # ['a', 'a', 'b', 'b', 'c', 'c']
## ['a', 'a', 'b', 'b', 'c', 'c']
# Índice fuera de rango
try:
print(letras[6]) # IndexError: list index out of range
except IndexError as e:
print(f"Error: {e}")
## Error: list index out of range
# Python no tiene equivalente al índice 0 de R que devuelve vacío
# El slicing [0:0] devuelve lista vacía
print(letras[0:0]) # []
## []
# En Python, la indexación negativa significa "desde el final"
# -1 = último elemento, -2 = penúltimo, etc.
# Para excluir elementos (equivalente a R), necesitamos approaches diferentes
# Excluir elementos específicos (usando list comprehension)
def excluir_indices(lista, indices_a_excluir):
return [item for i, item in enumerate(lista) if i not in indices_a_excluir]
# Todo excepto el primero
print(excluir_indices(letras, [0])) # ['b', 'c', 'd', 'e', 'f']
## ['b', 'c', 'd', 'e', 'f']
# Todo excepto el último
print(excluir_indices(letras, [5])) # ['a', 'b', 'c', 'd', 'e']
## ['a', 'b', 'c', 'd', 'e']
# Excluir múltiples elementos
print(excluir_indices(letras, [0, 2, 4])) # ['b', 'd', 'f']
## ['b', 'd', 'f']
# Excluir los primeros tres
print(excluir_indices(letras, [0, 1, 2])) # ['d', 'e', 'f']
## ['d', 'e', 'f']
# O usando slicing
print(letras[3:]) # ['d', 'e', 'f']
## ['d', 'e', 'f']
#INDEXACION POR NOMBRES
#Tratado como un mapa clave-valor.
notas <- c(matematicas = 85, ciencias = 92, historia = 78, ingles = 88)
# Un elemento por nombre
notas["matematicas"]
## matematicas
## 85
# Múltiples elementos por nombre
notas[c("matematicas", "ingles")]
## matematicas ingles
## 85 88
numeros <- c(12, 7, 23, 9, 45, 3, 18)
# Crear un diccionario (equivalente a vector nombrado de R)
notas = {"matematicas": 85, "ciencias": 92, "historia": 78, "ingles": 88}
# Un elemento por nombre
print(notas["matematicas"]) # 85
## 85
# Múltiples elementos por nombre (necesitamos comprensión de diccionario)
materias = ["matematicas", "ingles"]
notas_seleccionadas = {materia: notas[materia] for materia in materias}
print(notas_seleccionadas) # {'matematicas': 85, 'ingles': 88}
## {'matematicas': 85, 'ingles': 88}
# O usando dict() con comprensión
notas_seleccionadas = dict((materia, notas[materia]) for materia in materias)
print(notas_seleccionadas)
## {'matematicas': 85, 'ingles': 88}
#INDEXACION LOGICA
# Crear máscara lógica
mask <- numeros > 15
mask
## [1] FALSE FALSE TRUE FALSE TRUE FALSE TRUE
# Aplicar máscara
numeros[mask]
## [1] 23 45 18
# Directamente en una línea
numeros[numeros > 15]
## [1] 23 45 18
# Condiciones múltiples con operadores lógicos (& AND vectorizado, && short-circuit)
numeros[(numeros > 5) & (numeros < 20)]
## [1] 12 7 9 18
numeros[(numeros < 5) | (numeros > 40)]
## [1] 45 3
# Usar funciones en condiciones
numeros[numeros > mean(numeros)]
## [1] 23 45 18
# Máscara con NA
numeros_with_na <- c(12, NA, 23)
numeros_with_na[!is.na(numeros_with_na) & numeros_with_na > 15]
## [1] 23
import numpy as np
# Crear array similar al vector de R
numeros = np.array([10, 15, 20, 25, 30, 35, 40])
# Crear máscara lógica
mask = numeros > 15
print(mask) # [False False True True True True True]
## [False False True True True True True]
# Aplicar máscara
print(numeros[mask]) # [20 25 30 35 40]
## [20 25 30 35 40]
# Directamente en una línea
print(numeros[numeros > 15]) # [20 25 30 35 40]
## [20 25 30 35 40]
# Condiciones múltiples con operadores lógicos (& AND, | OR, ~ NOT)
print(numeros[(numeros > 5) & (numeros < 20)]) # [10 15]
## [10 15]
print(numeros[(numeros < 5) | (numeros > 40)]) # [] (array vacío)
## []
# Usar funciones en condiciones
print(numeros[numeros > np.mean(numeros)]) # [25 30 35 40]
## [30 35 40]