R es un lenguaje de alto nivel para análisis estadístico y computación de datos.
R fue desarrollado por Ross Ihaka y Robert Gentleman y se basa en el lenguaje S de Bell Labs (John Chambers).
Lugar: Universidad de Auckland, Nueva Zelanda
Motivo: S-PLUS muy costoso ($50,000 USD)
Liberación: 1995 bajo licencia GPL
CRAN (Comprehensive R Archive Network) 1997 (Kurt Hornik) : En términos simples, CRAN es el repositorio oficial y centralizado de paquetes para el lenguaje de programación R. Es el lugar de donde R y sus usuarios obtienen software, paquetes y documentación.
Python
Creador: Guido van Rossum (1989)
Lugar: CWI Amsterdam (Centro de Matemáticas e Informática)
Inspiración: Lenguaje ABC + Monty Python
Filosofía: “Zen de Python” (PEP 20)
CARACTERÍSTICAS TÉCNICAS
R - Fortalezas Estadísticas
Valores faltantes (NA) especializados
Factores para variables categóricas
Vectorización automática
Sintaxis de fórmulas estadísticas
Gráficos de calidad de publicación (ggplot2, lattice)
R es mejor para:- Estadística avanzada - Visualización de datos - Investigación académica - Análisis exploratorio
Python es mejor para:- Machine Learning - Producción/APIs - Automatización Integración de sistemas
¿Qué es una IDE?
Un IDE (Integrated Development Environment - Entorno de Desarrollo Integrado) es un software especializado que combina todas las herramientas necesarias para programar en una sola interfaz.
Analogía: Si programar fuera como construir una casa:
Editor de texto = Martillo y herramientas básicas
IDE = Taller completo con todas las herramientas organizadas
Características principales de un IDE
1. Editor de código inteligente
Resaltado de sintaxis por colores
Autocompletado automático
Indentación automática
Plegado de código (fold/unfold)
2. Depurador (Debugger)
Puntos de interrupción (breakpoints)
Ejecución paso a paso
Inspección de variables
Seguimiento de errores
3. Compilador/Intérprete integrado
Ejecución directa del código
Visualización de resultados
Consola integrada
4. Gestión de proyectos
Organización de archivos
Navegación entre archivos
Búsqueda en todo el proyecto
5. Integración con herramientas
Control de versiones (Git)
Terminal integrada
Gestión de paquetes/librerías
6. Personalización
Temas de colores
Atajos de teclado configurables
Extensiones y plugins
Algunos comandos para revisar la version de R y Python en la que estamos trabajando
R.version.string
[1] "R version 4.5.1 (2025-06-13 ucrt)"
R.version
_
platform x86_64-w64-mingw32
arch x86_64
os mingw32
crt ucrt
system x86_64, mingw32
status
major 4
minor 5.1
year 2025
month 06
day 13
svn rev 88306
language R
version.string R version 4.5.1 (2025-06-13 ucrt)
nickname Great Square Root
17%%5# Módulo: 2 (es decir el resto de la división)
[1] 2
17%/%5# División entera: 3 (es decir la parte entera de la división)
[1] 3
sqrt(9) # Raíz cuadrada: 3
[1] 3
abs(-5) # Valor absoluto: 5
[1] 5
17%5# Módulo: 2
2
17//5# División entera: 3
3
#Para algunas funciones en python como la raiz necesitamos importar la libreria math.import mathmath.sqrt(9) # Raíz cuadrada: 3.0
3.0
abs(-5) # Valor absoluto: 5
5
1.3. Funciones matemáticas
sin(pi/2) # Seno: 1
[1] 1
log(10) # Log natural: 2.302585
[1] 2.302585
log10(100) # Log base 10: 2
[1] 2
exp(1) # Exponencial: 2.718282
[1] 2.718282
round(pi, 4) # Redondeo: 3.1416
[1] 3.1416
import mathmath.sin(math.pi/2) # Seno: 1.0
1.0
math.log(10) # Log natural: 2.302585092994046
2.302585092994046
math.log10(100) # Log base 10: 2.0
2.0
math.exp(1) # Exponencial: 2.718281828459045
2.718281828459045
round(math.pi, 4) # Redondeo: 3.1416
3.1416
2. Asignación de variables
2.1. Métodos de asignación
x <-5# Asignación estándary =10# Asignación con =15-> z # Asignación hacia derecha(resultado <-2+3) # Asignación con impresión: 5 (los parentesis ejecutan el print)
[1] 5
x =5# Asignación estándary =10# Asignación con =# No hay asignación hacia derecharesultado =2+3print(resultado) # 5
5
2.2. Reglas de nomenclatura
R:
Comienzan con letra o punto
Pueden contener letras, números, puntos y guiones bajos
Sensible a mayúsculas
Python:
Comienzan con letra o guión bajo
Pueden contener letras, números y guiones bajos
Sensible a mayúsculas
2.3. Palabras reservadas
No podrás usar como nombre de la variable a las siguientes palabras:
R: TRUE, FALSE, NULL, Inf, NaN, NA, if, else, function, for, etc. Python: True, False, None, if, else, def, for, while, etc.
3. Gestión del Espacio de Trabajo
3.1. Listar y eliminar objetos
ls() # Listar objetos
[1] "resultado" "x" "y" "z"
ls(pattern ="var") # Listar con patrón
character(0)
rm(x, y) # Eliminar objetosrm(list =ls()) # Eliminar todos
#Para el uso de vectores en Python requerimos la libreria de numpyimport numpy as npnumeros = np.array([1, 3, 5, 7, 9]) # Array numéricocolores = ["rojo", "verde", "azul"] # Lista de stringslist(range(1, 11)) # Secuencia: [1, 2, 3, ..., 10]
Una matriz es un caso particular de array bidimensional (filas y columnas) especializado en operaciones de álgebra lineal como multiplicación matricial, cálculo de determinantes, inversas y resolución de sistemas de ecuaciones, siendo fundamental en aplicaciones como gráficos por computadora, procesamiento de imágenes y machine learning.
Un array es una estructura de datos que almacena una colección de elementos del mismo tipo organizados en una o más dimensiones (vectores, matrices o tensores), permitiendo acceso eficiente mediante índices y operaciones numéricas rápidas, ideal para manejar datos científicos, señales, imágenes o cualquier conjunto homogéneo de valores en programación.
import numpy as nparr = np.arange(1, 25).reshape(2, 3, 4)arr[0, 1, 2] # Elemento: 15 (índices base 0)
np.int64(7)
9. Valores Especiales
NA# Valor faltante
[1] NA
NaN# No es un número
[1] NaN
Inf# Infinito
[1] Inf
NULL# Ausencia de valor
NULL
is.na(NA) # TRUE
[1] TRUE
is.nan(0/0) # TRUE
[1] TRUE
is.finite(Inf) # FALSE
[1] FALSE
import numpy as npnp.nan # No es un número
nan
np.inf # Infinito
inf
None# Ausencia de valornp.isnan(np.nan) # True
np.True_
np.isfinite(np.inf) # False
np.False_
10. Listas y Estructuras de Datos
10.1. Listas
Una lista es una estructura de datos ordenada y mutable que permite almacenar una colección de elementos de diferentes tipos (números, texto, otras listas, etc.) bajo un mismo nombre, accesibles mediante un índice numérico.
irve para agrupar, organizar y manipular múltiples elementos de manera flexible, permitiendo operaciones como agregar, eliminar, modificar y acceder a valores específicos, lo que la hace ideal para manejar conjuntos de datos variables, iterar sobre elementos con bucles y almacenar información heterogénea en programación.
lista <-list(a =1, b ="texto", c =matrix(1:4, 2))lista[[2]] # Acceso por índice: "texto"
[1] "texto"
lista$b # Acceso por nombre: "texto"
[1] "texto"
lista = {"a": 1, "b": "texto", "c": np.array([[1, 2], [3, 4]])}lista["b"] # Acceso por clave: "texto"
Un DataFrame es una estructura de datos bidimensional (similar a una tabla de Excel o una tabla de base de datos) que organiza la información en filas (observaciones o registros) y columnas (variables o características), donde cada columna puede contener un tipo de dato diferente (números, texto, fechas, etc.).
Sirve para almacenar, manipular y analizar datos de manera eficiente, permitiendo operaciones como filtrado, ordenamiento, agrupación, limpieza de datos, cálculos estadísticos y visualización, siendo fundamental en el proceso de análisis y ciencia de datos en lenguajes como Python (con la librería Pandas) y R.
#Ejemplo de solicitud de ayuda del argumento 'mean'?mean # Ayuda de función
starting httpd help server ... done
help(mean) # Ayuda de función??mean # Búsqueda ampliaexample(mean) # Ejemplos
mean> x <- c(0:10, 50)
mean> xm <- mean(x)
mean> c(xm, mean(x, trim = 0.10))
[1] 8.75 5.50
args(mean) # Argumentos
function (x, ...)
NULL
help(np.mean) # Ayuda de función
Help on _ArrayFunctionDispatcher in module numpy:
mean(a, axis=None, dtype=None, out=None, keepdims=<no value>, *, where=<no value>)
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
np.mean.__doc__ # Documentación
'\n Compute the arithmetic mean along the specified axis.\n\n Returns the average of the array elements. The average is taken over\n the flattened array by default, otherwise over the specified axis.\n `float64` intermediate and return values are used for integer inputs.\n\n Parameters\n ----------\n a : array_like\n Array containing numbers whose mean is desired. If `a` is not an\n array, a conversion is attempted.\n axis : None or int or tuple of ints, optional\n Axis or axes along which the means are computed. The default is to\n compute the mean of the flattened array.\n\n If this is a tuple of ints, a mean is performed over multiple axes,\n instead of a single axis or all the axes as before.\n dtype : data-type, optional\n Type to use in computing the mean. For integer inputs, the default\n is `float64`; for floating point inputs, it is the same as the\n input dtype.\n out : ndarray, optional\n Alternate output array in which to place the result. The default\n is ``None``; if provided, it must have the same shape as the\n expected output, but the type will be cast if necessary.\n See :ref:`ufuncs-output-type` for more details.\n See :ref:`ufuncs-output-type` for more details.\n\n keepdims : bool, optional\n If this is set to True, the axes which are reduced are left\n in the result as dimensions with size one. With this option,\n the result will broadcast correctly against the input array.\n\n If the default value is passed, then `keepdims` will not be\n passed through to the `mean` method of sub-classes of\n `ndarray`, however any non-default value will be. If the\n sub-class\' method does not implement `keepdims` any\n exceptions will be raised.\n\n where : array_like of bool, optional\n Elements to include in the mean. See `~numpy.ufunc.reduce` for details.\n\n .. versionadded:: 1.20.0\n\n Returns\n -------\n m : ndarray, see dtype parameter above\n If `out=None`, returns a new array containing the mean values,\n otherwise a reference to the output array is returned.\n\n See Also\n --------\n average : Weighted average\n std, var, nanmean, nanstd, nanvar\n\n Notes\n -----\n The arithmetic mean is the sum of the elements along the axis divided\n by the number of elements.\n\n Note that for floating-point input, the mean is computed using the\n same precision the input has. Depending on the input data, this can\n cause the results to be inaccurate, especially for `float32` (see\n example below). Specifying a higher-precision accumulator using the\n `dtype` keyword can alleviate this issue.\n\n By default, `float16` results are computed using `float32` intermediates\n for extra precision.\n\n Examples\n --------\n >>> import numpy as np\n >>> a = np.array([[1, 2], [3, 4]])\n >>> np.mean(a)\n 2.5\n >>> np.mean(a, axis=0)\n array([2., 3.])\n >>> np.mean(a, axis=1)\n array([1.5, 3.5])\n\n In single precision, `mean` can be inaccurate:\n\n >>> a = np.zeros((2, 512*512), dtype=np.float32)\n >>> a[0, :] = 1.0\n >>> a[1, :] = 0.1\n >>> np.mean(a)\n np.float32(0.54999924)\n\n Computing the mean in float64 is more accurate:\n\n >>> np.mean(a, dtype=np.float64)\n 0.55000000074505806 # may vary\n\n Computing the mean in timedelta64 is available:\n\n >>> b = np.array([1, 3], dtype="timedelta64[D]")\n >>> np.mean(b)\n np.timedelta64(2,\'D\')\n\n Specifying a where argument:\n\n >>> a = np.array([[5, 9, 13], [14, 10, 12], [11, 15, 19]])\n >>> np.mean(a)\n 12.0\n >>> np.mean(a, where=[[True], [False], [False]])\n 9.0\n\n '
# Ejemplos usualmente en documentación onlineimport inspect #Libreria para gestionar la ayuda de argumentosinspect.signature(np.mean) # Argumentos