Primeros pasos

Introducción a R

R es un lenguaje de alto nivel….

caracteristicas de R

-interpretado ( no complicado)

-open source

-comunidad activa

#version 
R.version.string
## [1] "R version 4.5.1 (2025-06-13 ucrt)"
#informacion completa
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

Directorio de trabajo

#observar directorio
getwd()
## [1] "C:/Users/Jamir/Documents"
##[1] "C:/Users/Jamir/Documents"
#cambiar el directorio
#setwd("C:/Users/Jamir/Desktop/Curso_programacion")
getwd()
## [1] "C:/Users/Jamir/Documents"

Asignar el directorio automaticamente donde se encuentra el documento guardado.

knitr::opts_knit$set(root.dir = dirname(rstudioapi::getActiveDocumentContext()$path))

operaciones basicas

#suma

9+1
## [1] 10
#resta
12-2
## [1] 10
#division
44/7
## [1] 6.285714
#parenteisis modifica el orden
40/(22-2)
## [1] 2
#potenciacion
4^2
## [1] 16
#potnciacin mas usada
4**2
## [1] 16
#resto y division entera
17%%5
## [1] 2
17%/%5
## [1] 3

Funciones matematicas

#raiz cuadrada
sqrt(64)
## [1] 8
#valor absoluto
abs(-27)
## [1] 27
#funcion trigonometrica seno(pi)
sin(pi/2)
## [1] 1
#funcion trigonometrica coseno
cos(0)
## [1] 1
#logaritmico
log(10)
## [1] 2.302585
#logaritmico base 10
log10(100)
## [1] 2
log(10,base=4)
## [1] 1.660964
#exponencial
exp(1)
## [1] 2.718282
#otras fucniones round
round(pi,2) #round(digits=2,pi)
## [1] 3.14

notacion cientifica

#numero grande
2324511042900
## [1] 2.324511e+12
#numero muy pequeño
0.000000002581
## [1] 2.581e-09
#forzar notacion cientifica
format(123456,scientific=TRUE)
## [1] "1.23456e+05"
#suprimir notificacion cientifica
options(scipen =999)
#restaurar 
options(scipen=0)

sistema de ayuda

#ayuda en funciones especificas
?sqrt
## starting httpd help server ... done
help(sqrt)
#buscar documentacion
??sqrt
help.search("sqrt")

Ayuda sobre operadores

?"**"
help("**")
#example de alguna funcion
example(abs)
## 
## abs> require(stats) # for spline
## 
## abs> require(graphics)
## 
## abs> xx <- -9:9
## 
## abs> plot(xx, sqrt(abs(xx)),  col = "red")

## 
## abs> lines(spline(xx, sqrt(abs(xx)), n=101), col = "pink")
## abs> lines(spline(xx, sqrt(abs(xx)), n=101), col = "pink")
# Argumento de la función
args(abs)
## function (x) 
## NULL
args(round)
## function (x, digits = 0, ...) 
## NULL

Aplicaciones numericas aritmetica y asignicacion

#para asginar tradicionalemte "<-"
x<-20
#mostarar 
x
## [1] 20
print(x)
## [1] 20
#metodo alternativo"="
y=30
y
## [1] 30
#asignacion a la derecha
40->z
z
## [1] 40
#mostrar el valor de manera inmediate
(w<-50)
## [1] 50

palabras reservadas TRUE,FALSE,NULL,INF,NaN,NA…

?reserved
?FALSE

gestion wordpace

# Listar todo lo que se tienes guardado
ls()
## [1] "w"  "x"  "xx" "y"  "z"
# Obtener información (estructura) objeto
str(x)
##  num 20
# Eliminar objetos especifcos
rm(y)

# Eliminar todo
rm(list=ls())

vectores y escalares

#escalar asignar
edad<-20

vector

es una secuencia de datos,que tienen un mismo tipo de dato

#crear un vector  
vector<-c(21,22,23,24,29)
vector
## [1] 21 22 23 24 29
#crear un vector de caracteres
vector<-c(12,"hola", 24)
vector
## [1] "12"   "hola" "24"
color<-c("azul","verde", "amarrillo")
color
## [1] "azul"      "verde"     "amarrillo"
#crearun vector a partir de calculos
vector3<-c(23+2,sqrt(64),abs(-23),52/3)
vector3
## [1] 25.00000  8.00000 23.00000 17.33333
#combinar de vector
v1<-c(1,2,3)
v2<-c(4,5,6)
v3<-c(v1,v2)
v3
## [1] 1 2 3 4 5 6
#clase de vector
class(vector)
## [1] "character"
class(vector3)
## [1] "numeric"
class(color)
## [1] "character"
class(color)
## [1] "character"
class(v3)
## [1] "numeric"
vector4<-c(40,"hola",50)
vector4
## [1] "40"   "hola" "50"
class(vector4)
## [1] "character"

operadores de secuencias

1:10
##  [1]  1  2  3  4  5  6  7  8  9 10
#descendente
15:10
## [1] 15 14 13 12 11 10
#negativos
-5:5
##  [1] -5 -4 -3 -2 -1  0  1  2  3  4  5
#con decimales
1.5:5.8
## [1] 1.5 2.5 3.5 4.5 5.5

utilizando la funcion seq

#incremte especifico
seq(from=0, to=10,by=2)
## [1]  0  2  4  6  8 10
seq(from=0, to=10, by=0.2)
##  [1]  0.0  0.2  0.4  0.6  0.8  1.0  1.2  1.4  1.6  1.8  2.0  2.2  2.4  2.6  2.8
## [16]  3.0  3.2  3.4  3.6  3.8  4.0  4.2  4.4  4.6  4.8  5.0  5.2  5.4  5.6  5.8
## [31]  6.0  6.2  6.4  6.6  6.8  7.0  7.2  7.4  7.6  7.8  8.0  8.2  8.4  8.6  8.8
## [46]  9.0  9.2  9.4  9.6  9.8 10.0
#por numero elemento
seq(from=0,to=10,length.out=20)
##  [1]  0.0000000  0.5263158  1.0526316  1.5789474  2.1052632  2.6315789
##  [7]  3.1578947  3.6842105  4.2105263  4.7368421  5.2631579  5.7894737
## [13]  6.3157895  6.8421053  7.3684211  7.8947368  8.4210526  8.9473684
## [19]  9.4736842 10.0000000
#generar secuencia de manera descendete
seq(from=10,to=0,by=-1)
##  [1] 10  9  8  7  6  5  4  3  2  1  0

funcion repetición

rep(20,times=5)
## [1] 20 20 20 20 20
#repetir un valor completo
rep(c(21,23), each=3)
## [1] 21 21 21 23 23 23
#combinar times y each
rep(c("rojo","azul"), times=3, each=4)
##  [1] "rojo" "rojo" "rojo" "rojo" "azul" "azul" "azul" "azul" "rojo" "rojo"
## [11] "rojo" "rojo" "azul" "azul" "azul" "azul" "rojo" "rojo" "rojo" "rojo"
## [21] "azul" "azul" "azul" "azul"
#indexion

indexion

#longitud de un vector
length(vector)
## [1] 3
#extraer un elemento
vector5<-c(14,15,13)
vector5
## [1] 14 15 13
#extraer elemento de la posicion 1
vector5[1]
## [1] 14
#extraer ek tercer elemento
vector5[3]
## [1] 13
#extraer secuecnia de elemento desde el 1 al 2
vector5[1:2]
## [1] 14 15
#extraer el sguendo y el ultimo elelemnto
vector5[c(2,3)]
## [1] 15 13
#extraer en iorden inverso
vector5[-1]
## [1] 15 13

Matrices y arreglos

#generar matriz
matrix(1:16,nrow=4)
##      [,1] [,2] [,3] [,4]
## [1,]    1    5    9   13
## [2,]    2    6   10   14
## [3,]    3    7   11   15
## [4,]    4    8   12   16
matrix(1:16,nrow=4,byrow=TRUE)
##      [,1] [,2] [,3] [,4]
## [1,]    1    2    3    4
## [2,]    5    6    7    8
## [3,]    9   10   11   12
## [4,]   13   14   15   16
mi_matriz = matrix(1:16, nrow=4, byrow = TRUE)
mi_matriz
##      [,1] [,2] [,3] [,4]
## [1,]    1    2    3    4
## [2,]    5    6    7    8
## [3,]    9   10   11   12
## [4,]   13   14   15   16
# Funciones básicas
# dimensiones
dim(mi_matriz)
## [1] 4 4
nrow(mi_matriz)
## [1] 4
ncol(mi_matriz)
## [1] 4
# Indexación
matriz2<-matrix(1:20, nrow=4, byrow = TRUE)
matriz2
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    2    3    4    5
## [2,]    6    7    8    9   10
## [3,]   11   12   13   14   15
## [4,]   16   17   18   19   20
# Extrer el 7
matriz2[2,2]
## [1] 7
# Extrer el 20
matriz2[4,5]
## [1] 20

Broadcasting (operaciones)

matriz2+10
##      [,1] [,2] [,3] [,4] [,5]
## [1,]   11   12   13   14   15
## [2,]   16   17   18   19   20
## [3,]   21   22   23   24   25
## [4,]   26   27   28   29   30
matriz2**2
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    4    9   16   25
## [2,]   36   49   64   81  100
## [3,]  121  144  169  196  225
## [4,]  256  289  324  361  400
# Multiplicación matricial
matriz1<-matrix(1:12, nrow = 4)
matriz1
##      [,1] [,2] [,3]
## [1,]    1    5    9
## [2,]    2    6   10
## [3,]    3    7   11
## [4,]    4    8   12
matriz2<-matrix(13:24, nrow = 3)
matriz2
##      [,1] [,2] [,3] [,4]
## [1,]   13   16   19   22
## [2,]   14   17   20   23
## [3,]   15   18   21   24
matriz1%*%matriz2
##      [,1] [,2] [,3] [,4]
## [1,]  218  263  308  353
## [2,]  260  314  368  422
## [3,]  302  365  428  491
## [4,]  344  416  488  560

Data frame

data.frame(matrix(1:16, nrow=4))
##   X1 X2 X3 X4
## 1  1  5  9 13
## 2  2  6 10 14
## 3  3  7 11 15
## 4  4  8 12 16
df <- data.frame(nombre=c("Maryorie", "Jorge"), edad=c(20,22))
df
##     nombre edad
## 1 Maryorie   20
## 2    Jorge   22

Importar desde Github

# Importar datos desde github
df <- read.csv(
  "https://raw.githubusercontent.com/jamirmanama-lab/BASE-DE-DATOS-EJEMPLOS/refs/heads/main/Precios%20de%20Clorhidrato.csv",
  sep = ";",
  encoding = "UTF-8"
)

head(df, 2)
##               ZEI Enero..2020. Abril..2020. Mayo..2020. Junio..2020.
## 1           VRAEM    5,922.26     2,425.74    2,940.19     3,457.68 
## 2 Triple Frontera    5,147.00     5,133.43    5,763.00     6,174.40 
##   Julio..2020. Agosto..2020. Setiembre..2020. Octubre..2020. Noviembre..2020.
## 1    4,450.36      4,395.71         4,177.14       4,468.75         4,300.00 
## 2    6,174.40      4,559.40         4,994.60       4,856.25         5,145.00 
##   Diciembre...2020. Enero..2021. Febrero..2021. Marzo..2021. Abril..2021.
## 1         4,202.50     4,084.07       3,783.21     3,676.88     3,700.00 
## 2         5,285.00     5,227.20       5,385.60     5,819.18     5,905.20 
##   Mayo..2021. Junio..2021. Julio..2021. Agosto..2021. Setiembre..2021.
## 1   3,906.70     3,854.13     3,958.46      3,968.53         4,067.43 
## 2   5,490.00     5,547.85     5,842.05      6,304.62         5,497.13 
##   Octubre..2021. Noviembre..2021. Diciembre..2021. Enero..2022. Febrero..2022.
## 1      4,005.37         4,009.23         3,799.00     3,482.27       3,532.23 
## 2      5,145.95         6,691.29         6,990.31     6,476.38       5,766.05 
##   Marzo..2022. Abril..2022. Mayo..2022. Junio..2022. Julio..2022. Agosto..2022.
## 1    3,361.01     3,272.39    3,388.56     3,036.80     3,132.97      3,631.51 
## 2    5,225.25     5,343.01    6,103.97     6,118.20     6,543.36      6,113.46 
##   Setiembre..2022. Octubre..2022. Noviembre..2022. Diciembre..2022.
## 1        3,538.99       3,315.00         2,972.26         3,213.64 
## 2        8,102.73       8,137.00         7,950.86         7,960.47 
##   Enero..2023. Febrero..2023. Marzo..2023. Abril..2023. Mayo..2023.
## 1    3,178.33       3,357.09     3,361.45     3,749.83    3,693.00 
## 2    7,904.52       7,966.69     7,200.95     8,129.46    8,466.20 
##   Junio..2023. Julio..2023. Agosto..2023. Setiembre..2023. Octubre..2023.
## 1    3,869.51     4,938.85      5,182.22         5,793.84       6,102.42 
## 2    7,815.62     7,679.55      8,130.96         7,907.11       8,096.26 
##   Noviembre..2023. Diciembre..2023.
## 1        5,760.45         5,550.63 
## 2        8,260.41         8,432.60
#importar datos desde kaggle
# Importar datos de Kaggle
df <- read.csv(
  "C:/Users/Jamir/Downloads/ncr_ride_bookings.csv",
  header = TRUE,
  sep = ",",
  encoding = "UTF-8"
)

# Mostrar solo las primeras 5 filas
head(df, 2)
##         Date     Time   Booking.ID  Booking.Status  Customer.ID Vehicle.Type
## 1 2024-03-23 12:29:38 "CNR5884300" No Driver Found "CID1982111"        eBike
## 2 2024-11-29 18:01:39 "CNR1326809"      Incomplete "CID4604802"     Go Sedan
##   Pickup.Location     Drop.Location Avg.VTAT Avg.CTAT
## 1     Palam Vihar           Jhilmil     null     null
## 2   Shastri Nagar Gurgaon Sector 56      4.9     14.0
##   Cancelled.Rides.by.Customer Reason.for.cancelling.by.Customer
## 1                        null                              null
## 2                        null                              null
##   Cancelled.Rides.by.Driver Driver.Cancellation.Reason Incomplete.Rides
## 1                      null                       null             null
## 2                      null                       null                1
##   Incomplete.Rides.Reason Booking.Value Ride.Distance Driver.Ratings
## 1                    null          null          null           null
## 2       Vehicle Breakdown           237          5.73           null
##   Customer.Rating Payment.Method
## 1            null           null
## 2            null            UPI

Importar desde INEI

# Descargar base de datos desde la INEI
df <- read.csv(
  "C:/Users/Jamir/Downloads/Enaho01-2022-100.csv",
  header = TRUE,
  sep = ",",
  encoding = "latin1"
)

# Mostrar solo las primeras 5 filas
head(df, 2)
##    AÑO MES CONGLOME VIVIENDA HOGAR UBIGEO DOMINIO ESTRATO PERIODO TIPENC
## 1 2022   2     5007        3    11  10101       4       4       1      3
## 2 2022   2     5007       12    11  10101       4       4       1      3
##     FECENT RESULT PANEL P22 P23 P24A P24B P25.1 P25.2 P25.3 P25.4 P25.5 P101
## 1 20220220      1     1   2  NA    3    1     1     0     1     1     0    1
## 2 20220203      1     1   2  NA    2    1     1     0     1     1     0    4
##   P102 P103 P103A P104 P104A P104B1 P104B2 P105A P105B P106 P106A P106B P107B1
## 1    3    3     2    1     0      3      3     1   376   NA    NA    NA      2
## 2    4    5     2    1     1      3      2     5    NA  166    NA    NA      2
##   P107C11 P107C12 P107C13 P107C14 P107C16 P107C17 P107C18 P107C19 P107C110
## 1      NA      NA      NA      NA      NA      NA      NA      NA       NA
## 2      NA      NA      NA      NA      NA      NA      NA      NA       NA
##   P107D1 P107B2 P107C21 P107C22 P107C23 P107C24 P107C26 P107C27 P107C28 P107C29
## 1     NA      2      NA      NA      NA      NA      NA      NA      NA      NA
## 2     NA      2      NA      NA      NA      NA      NA      NA      NA      NA
##   P107C210 P107D2 P107B3 P107C31 P107C32 P107C33 P107C34 P107C36 P107C37
## 1       NA     NA      2      NA      NA      NA      NA      NA      NA
## 2       NA     NA      2      NA      NA      NA      NA      NA      NA
##   P107C38 P107C39 P107C310 P107D3 P107B4 P107C41 P107C42 P107C43 P107C44
## 1      NA      NA       NA     NA      2      NA      NA      NA      NA
## 2      NA      NA       NA     NA      2      NA      NA      NA      NA
##   P107C46 P107C47 P107C48 P107C49 P107C410 P107D4 P107E P110 P110A1 P110A
## 1      NA      NA      NA      NA       NA     NA    NA    1      1     1
## 2      NA      NA      NA      NA       NA     NA    NA    2      1     1
##   P110A_MODIFICADA P110C P110C1 P110C2 P110C3 P110D P110E P110F P110G P111A
## 1              1.2     1     24     NA     NA     2     1     1     1     1
## 2              0.8     1     24     NA     NA     1     1     1     1     2
##   P1121 P1123 P1124 P1125 P1126 P1127 P112A P1131 P1132 P1133 P1135 P1136 P1139
## 1     1     0     0     0     0     0     2     0     0     0     0     0     0
## 2     1     0     0     0     0     0     2     0     0     0     0     0     0
##   P1137 P1138 P113A P1141 P1142 P1143 P1144 P1145 P1171.01 P1171.02 P1171.04
## 1     0     1    NA     0     1     0     1     0        1        1        0
## 2     0     1    NA     0     1     0     1     0        1        1        0
##   P1171.05 P1171.06 P1171.07 P1171.08 P1171.09 P1171.10 P1171.11 P1171.12
## 1        0        0        0        0        0        0        0        1
## 2        0        0        0        0        0        0        0        1
##   P1171.13 P1171.14 P1171.15 P1171.16 P1172.01 P1172.02 P1172.04 P1172.05
## 1        0        1        0        0        0        0       NA       NA
## 2        0        1        0        0        6       13       NA       NA
##   P1172.06 P1172.07 P1172.08 P1172.09 P1172.10 P1172.11 P1172.12 P1172.13
## 1       NA       NA       NA       NA       NA       NA       50       NA
## 2       NA       NA       NA       NA       NA       NA       10       NA
##   P1172.14 P1172.15 P1172.16 P1173.01 P1173.02 P1173.04 P1173.05 P1173.06
## 1       50       NA       NA        0        0       NA       NA       NA
## 2       20       NA       NA        0        0       NA       NA       NA
##   P1173.07 P1173.08 P1173.09 P1173.10 P1173.11 P1173.12 P1173.13 P1173.14
## 1       NA       NA       NA       NA       NA        0       NA        0
## 2       NA       NA       NA       NA       NA        0       NA        0
##   P1173.15 P1173.16 P1174.01 P1174.02 P1174.04 P1174.05 P1174.06 P1174.07
## 1       NA       NA       NA       NA       NA       NA       NA       NA
## 2       NA       NA       NA       NA       NA       NA       NA       NA
##   P1174.08 P1174.09 P1174.10 P1174.11 P1174.12 P1174.13 P1174.14 P1174.15
## 1       NA       NA       NA       NA       NA       NA       NA       NA
## 2       NA       NA       NA       NA       NA       NA       NA       NA
##   P1174.16 P1175.01 P1175.02 P1175.04 P1175.05 P1175.06 P1175.07 P1175.08
## 1       NA        1        1        0        0        0        0        0
## 2       NA        0        0        0        0        0        0        0
##   P1175.09 P1175.10 P1175.11 P1175.12 P1175.13 P1175.14 P1175.15 P1175.16
## 1        0        0        0        0        0        0        0        0
## 2        0        0        0        0        0        0        0        0
##   P117T2 P117T3 P117T4 T110 P200I P600I P600D1 P600M1 P600A1 P600D2 P600M2
## 1     99      0      0    1     1     1     19      1   2022      2      2
## 2     50      0      0    2     1     1     19      1   2022      2      2
##   P600A2 P612I1 P612I11 P612I2 P612I22 P700I P710I P800I P110I TICUEST01 D105B
## 1   2022      2      NA      2      NA     1     1     1     1         2  4527
## 2   2022      2      NA      2      NA     1     1     1     1         2    NA
##   D106 D107D1 D107D2 D107D3 D107D4 D1172.01 D1173.01 D1174.01 D1172.02 D1173.02
## 1   NA     NA     NA     NA     NA        0        0       NA        0        0
## 2 1999     NA     NA     NA     NA       72        0       NA      157        0
##   D1174.02 D1172.04 D1173.04 D1174.04 D1172.05 D1173.05 D1174.05 D1172.06
## 1       NA       NA       NA       NA       NA       NA       NA       NA
## 2       NA       NA       NA       NA       NA       NA       NA       NA
##   D1173.06 D1174.06 D1172.07 D1173.07 D1174.07 D1172.08 D1173.08 D1174.08
## 1       NA       NA       NA       NA       NA       NA       NA       NA
## 2       NA       NA       NA       NA       NA       NA       NA       NA
##   D1172.09 D1173.09 D1174.09 D1172.10 D1173.10 D1174.10 D1172.15 D1173.15
## 1       NA       NA       NA       NA       NA       NA       NA       NA
## 2       NA       NA       NA       NA       NA       NA       NA       NA
##   D1174.15 D1172.16 D1173.16 D1174.16 D612I11 D1172.11 D1173.11 D1174.11
## 1       NA       NA       NA       NA      NA       NA       NA       NA
## 2       NA       NA       NA       NA      NA       NA       NA       NA
##   D1172.12 D1173.12 D1174.12 D1172.13 D1173.13 D1174.13 D1172.14 D1173.14
## 1      605        0       NA       NA       NA       NA      605        0
## 2      121        0       NA       NA       NA       NA      242        0
##   D1174.14 D612I22 I105B I106 I1172.01 I1172.02 I1172.04 I1172.05 I1172.06
## 1       NA      NA  4527   NA        0        0       NA       NA       NA
## 2       NA      NA    NA 1999       72      157       NA       NA       NA
##   I1172.07 I1172.08 I1172.09 I1172.10 I1172.11 I1172.12 I1172.13 I1172.14
## 1       NA       NA       NA       NA       NA      605       NA      605
## 2       NA       NA       NA       NA       NA      121       NA      242
##   I1172.15 I1172.16 I1173.01 I1174.01 I1173.02 I1174.02 I1173.04 I1174.04
## 1       NA       NA        0       NA        0       NA       NA       NA
## 2       NA       NA        0       NA        0       NA       NA       NA
##   I1173.05 I1174.05 I1173.06 I1174.06 I1173.07 I1174.07 I1173.08 I1174.08
## 1       NA       NA       NA       NA       NA       NA       NA       NA
## 2       NA       NA       NA       NA       NA       NA       NA       NA
##   I1173.09 I1174.09 I1173.10 I1174.10 I1173.11 I1174.11 I1173.12 I1174.12
## 1       NA       NA       NA       NA       NA       NA        0       NA
## 2       NA       NA       NA       NA       NA       NA        0       NA
##   I1173.13 I1174.13 I1173.14 I1174.14 I1173.15 I1174.15 I1173.16 I1174.16 T111A
## 1       NA       NA        0       NA       NA       NA       NA       NA     1
## 2       NA       NA        0       NA       NA       NA       NA       NA     2
##   NBI1 NBI2 NBI3 NBI4 NBI5 FACTOR07 NCONGLOME SUB_CONGLOME CODCCPP
## 1    0    0    0    0    0 45.28237      7070            0       1
## 2    0    0    0    0    0 45.28237      7070            0       1
##              NOMCCPP  LONGITUD   LATITUD ALTITUD
## 1 CIUDAD CHACHAPOYAS -77.87392 -6.229049    2338
## 2 CIUDAD CHACHAPOYAS -77.87392 -6.229049    2338

Primeros pasos

Introducción a Python

Python es un lenguaje de programación de alto nivel, interpretado y multipropósito.

caracteristicas de R

-Portabilidad

-Multiproposito

-Tipo dinamico

-Sintaxis clara y legible

import sys
print(sys.version)
## 3.11.13 (main, Jul 11 2025, 22:36:59) [MSC v.1944 64 bit (AMD64)]

#información completa


``` python
import sys
print(sys.version)
## 3.11.13 (main, Jul 11 2025, 22:36:59) [MSC v.1944 64 bit (AMD64)]
print(sys.version_info)
## sys.version_info(major=3, minor=11, micro=13, releaselevel='final', serial=0)

#Directorio de Trabajo

import os

# Directorio actual
print("Directorio actual:", os.getcwd())
## Directorio actual: C:\Users\Jamir\Documents
import os

# Cambiar al nuevo directorio
os.chdir(r"C:\Users\Jamir\Desktop\Curso_programacion")

# Verificar que cambió
print("Nuevo directorio:", os.getcwd())
## Nuevo directorio: C:\Users\Jamir\Desktop\Curso_programacion

Operaciones básicas

#suma
2+1
## 3
#resta
10-1
## 9
#Multiplicación
2*2
## 4
#division
12/4
## 3.0
# Parentesis modifica el orden
87/(5+9)
## 6.214285714285714
# Potenciación
6**3
## 216
# Resto y división entera
17%5
## 2
17 // 5
## 3

Funciones matemáticas

# Raiz cuadrada
import math

x = 25
raiz = math.sqrt(x)
raiz
## 5.0
# Valor absoluto
x = -73
valor_absoluto = abs(x)
valor_absoluto
## 73
import math

# Seno de pi/2
resultado = math.sin(math.pi / 2)
print("sin(pi/2) =", resultado)
## sin(pi/2) = 1.0
import math

# Coseno de 0
resultado = math.cos(0)
print("cos(0) =", resultado)
## cos(0) = 1.0
import math

x = 10
resultado = math.log(x)  # logaritmo natural
print("log(10) (base e) =", resultado)
## log(10) (base e) = 2.302585092994046
import math

x = 100
resultado = math.log10(x)
print("log10(100) =", resultado)
## log10(100) = 2.0
import math

x = 10
base = 4
resultado = math.log(x, base)
resultado
## 1.6609640474436813
import math

resultado = math.exp(1)  # e^1
print("exp(1) =", resultado)
## exp(1) = 2.718281828459045
import math

resultado = round(math.pi, 2)
print("pi redondeado a 2 decimales =", resultado)
## pi redondeado a 2 decimales = 3.14

Notación cientifica

# Número grande
numero = 23245110429000080012300000000000000
numero
## 23245110429000080012300000000000000
# Número muy pequeño
numero_pequeno = 0.000000002581
numero_pequeno
## 2.581e-09
numero = 123456
resultado = format(numero, ".3e")  
print("Número en notación científica:", resultado)
## Número en notación científica: 1.235e+05
numero = 23245110429001230000000

#Suprimir notación científica (como scipen=999 en R)
print("Sin notación científica:", f"{numero:.0f}")
## Sin notación científica: 23245110429001229271040
# Restaurar comportamiento normal 
numero_float = float(numero)
numero_float
## 2.324511042900123e+22

Sistema de ayuda

# Ayuda en la función sqrt
help(abs)          
## Help on built-in function abs in module builtins:
## 
## abs(x, /)
##     Return the absolute value of the argument.
help
## Type help() for interactive help, or help(object) for help about object.
import math

# Mostrar la documentación de la función
help(math.sqrt)
## Help on built-in function sqrt in module math:
## 
## sqrt(x, /)
##     Return the square root of x.
help(int.__add__)
## Help on wrapper_descriptor:
## 
## __add__(self, value, /) unbound builtins.int method
##     Return self+value.
#ejemplo
# Ejemplos de abs()
print(abs(-10))  # 10
## 10
print(abs(5))    # 5
## 5
print(abs(-3.14))# 3.14
## 3.14
#argumento de la funcion
import inspect

# Ver argumentos de la función abs
print(inspect.signature(abs))
## (x, /)

Aplicaciones numéricas, aritmética y asignación

Asignación

# Asignar valor
x = 20

# Mostrar valor
print(x)
## 20
#Para asignar en Python solo se usa =
w = 50
print(w)
## 50

Palabras reservadas

import keyword

# Mostrar todas las palabras reservadas
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']

Gestión del workspace

# Listar todas las variables en el workspace
print(globals().keys())
## dict_keys(['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__', 'r', 'sys', 'os', 'math', 'x', 'raiz', 'valor_absoluto', 'resultado', 'base', 'numero', 'numero_pequeno', 'numero_float', 'inspect', 'w', 'keyword'])
x = 20
print("Estructura de x:", type(x))  # tipo de variable
## Estructura de x: <class 'int'>
print("Valor de x:", x)
## Valor de x: 20
x = 20
y = 100
z = 50
variables = [v for v in globals() if not v.startswith("__")]
print("Variables iniciales:", variables)
## Variables iniciales: ['r', 'sys', 'os', 'math', 'x', 'raiz', 'valor_absoluto', 'resultado', 'base', 'numero', 'numero_pequeno', 'numero_float', 'inspect', 'w', 'keyword', 'y', 'z']
 #Eliminar un objeto específico 

if "y" in globals():  # verificar que existe antes de eliminar
    del y
print("Variables después de eliminar y:", [v for v in globals() if not v.startswith("__")])
## Variables después de eliminar y: ['r', 'sys', 'os', 'math', 'x', 'raiz', 'valor_absoluto', 'resultado', 'base', 'numero', 'numero_pequeno', 'numero_float', 'inspect', 'w', 'keyword', 'z', 'variables']
#Eliminar todas las variables definidas (equivalente a rm(list=ls()))
for name in list(globals().keys()):
    if not name.startswith("__"):
        del globals()[name]

# Verificar workspace limpio
print("Workspace después de eliminar todo:", [v for v in globals() if not v.startswith("__")])
## Workspace después de eliminar todo: ['name']

Vectores y escalares

Escalar

Edad=20
Edad
## 20

Vector

Es una secuencia de datos, que tiene un mismo tipo de dato

# Crear un "vector" 
vector = [21, 23, 25, 27, 29]

# Mostrar el vector
print(vector)
## [21, 23, 25, 27, 29]
# Crear un "vector" de caracteres 
color = ["rojo", "Azul", "verde"]

# Mostrar el vector
print(color)
## ['rojo', 'Azul', 'verde']
import math  # para sqrt()

# Crear un vector a partir de cálculos
vector3 = [74 + 5, math.sqrt(25), abs(-23), 84 / 7]

# Mostrar el vector
print(vector3)
## [79, 5.0, 23, 12.0]
# Crear vectores
v1 = [1, 2, 3]
v2 = [4, 5, 6]

# Combinar vectores
v3 = v1 + v2

# Mostrar resultado
print(v3)
## [1, 2, 3, 4, 5, 6]
# Supongamos que tenemos un vector
vector = [21, 23, 25, 27, 29]

# Ver la "clase" del vector
type(vector)
## <class 'list'>
vector4=[40, "hola" ,50]
vector4
## [40, 'hola', 50]
print(type(vector4))
## <class 'list'>

operador para secuencias

 # Secuencia de 1 a 10
secuencia = list(range(1, 11))
print(secuencia)
## [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Secuencia descendente de 15 a 10
secuencia_desc = list(range(15, 9, -1))
print(secuencia_desc)
## [15, 14, 13, 12, 11, 10]
# Secuencia de -5 a 5
secuencia_neg = list(range(-5, 6))
print(secuencia_neg)
## [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
import numpy as np

# Secuencia de 1.5 a 5.5 con paso 1
secuencia_decimal = np.arange(1.5, 6.5, 1)  
print(secuencia_decimal)
## [1.5 2.5 3.5 4.5 5.5]

Utilizando np.arange()

import numpy as np

# Equivalente a seq(from=0, to=10, by=2)
secuencia = np.arange(0, 11, 2) 
print(secuencia)
## [ 0  2  4  6  8 10]

#Para un número especifico de elementos

secuencia = np.linspace(0, 10, 20)  
print(secuencia)
## [ 0.          0.52631579  1.05263158  1.57894737  2.10526316  2.63157895
##   3.15789474  3.68421053  4.21052632  4.73684211  5.26315789  5.78947368
##   6.31578947  6.84210526  7.36842105  7.89473684  8.42105263  8.94736842
##   9.47368421 10.        ]
import numpy as np

# Secuencia descendente de 10 a 0
secuencia_desc = np.arange(10, -1, -1)  # start=10, stop=-1 (para incluir 0), step=-1
print(secuencia_desc)
## [10  9  8  7  6  5  4  3  2  1  0]

Función de repetición

# Repetir un valor 5 veces
repetido = [20] * 5
print(repetido)
## [20, 20, 20, 20, 20]
vector = [21, 23]

# Repetir cada elemento 3 veces
repetido = [x for x in vector for _ in range(3)]
print(repetido)
## [21, 21, 21, 23, 23, 23]
colores = ["Rojo", "Azul"]

# Repetir cada elemento 2 veces, y repetir todo 3 veces
repetido = [x for _ in range(3) for x in colores for _ in range(2)]
print(repetido)
## ['Rojo', 'Rojo', 'Azul', 'Azul', 'Rojo', 'Rojo', 'Azul', 'Azul', 'Rojo', 'Rojo', 'Azul', 'Azul']

indexación

# Vector ejemplo
vector = [21, 23, 25, 27, 29]

# Obtener longitud del vector
longitud = len(vector)
print(longitud)
## 5
# Vector ejemplo
vector5 = [14, 15, 18, 19, 21]

# Extraer el primer elemento (posición 1 en R → índice 0 en Python)
primer_elemento = vector5[0]
print(primer_elemento)
## 14
# Vector ejemplo
vector5 = [14, 15, 18, 19, 21]

tercer_elemento = vector5[2]
print(tercer_elemento)
## 18
# Vector ejemplo
vector5 = [14, 15, 18, 19, 21]

# Extraer elementos desde posición 2 hasta 4 en R → índices 1 a 4 en Python
subvector = vector5[1:4]  # índice 1 incluido, índice 4 excluido
print(subvector)
## [15, 18, 19]
# Vector ejemplo
vector5 = [14, 15, 18, 19, 21]

# Extraer el 1er, 3er y último elemento
elementos = [vector5[i] for i in [0, 2, 4]]
print(elementos)
## [14, 18, 21]
vector5 = [14, 15, 18, 19, 21]

# Todos excepto el primer elemento
sin_primero = vector5[1:]
print(sin_primero)
## [15, 18, 19, 21]

Matrices y arreglos

import numpy as np

# Crear matriz 4x4 con números del 1 al 16
matriz = np.arange(1, 17).reshape(4, 4)
print(matriz)
## [[ 1  2  3  4]
##  [ 5  6  7  8]
##  [ 9 10 11 12]
##  [13 14 15 16]]
import numpy as np

# Crear vector del 1 al 16
vector = np.arange(1, 17)

# Convertir en matriz 4x4, rellenando por filas
matriz = vector.reshape(4, 4)  # Por defecto rellena por filas
print(matriz)
## [[ 1  2  3  4]
##  [ 5  6  7  8]
##  [ 9 10 11 12]
##  [13 14 15 16]]
import numpy as np

# Crear matriz 4x4 rellenando por filas (byrow=TRUE)
mi_matriz = np.arange(1, 17).reshape(4, 4)
print(mi_matriz)
## [[ 1  2  3  4]
##  [ 5  6  7  8]
##  [ 9 10 11 12]
##  [13 14 15 16]]
import numpy as np

# Matriz 
mi_matriz = np.arange(1, 17).reshape(4, 4)

# Dimensiones de la matriz
dimensiones = mi_matriz.shape
print(dimensiones)
## (4, 4)
import numpy as np

# Matriz 
mi_matriz = np.arange(1, 17).reshape(4, 4)

# Número de filas
n_filas = mi_matriz.shape[0]
print(n_filas)
## 4
import numpy as np

# Matriz 
mi_matriz = np.arange(1, 17).reshape(4, 4)

# Número de columnas
n_columnas = mi_matriz.shape[1]
print(n_columnas)
## 4
import numpy as np

# Crear matriz 4x5 con números del 1 al 20, rellenando por filas
matriz2 = np.arange(1, 21).reshape(4, 5)
print(matriz2)
## [[ 1  2  3  4  5]
##  [ 6  7  8  9 10]
##  [11 12 13 14 15]
##  [16 17 18 19 20]]
import numpy as np

# Matriz  4x5
matriz2 = np.arange(1, 21).reshape(4, 5)

# Extraer el 7
elemento = matriz2[1, 1]
print(elemento)
## 7

Broadcasting (operaciones)

import numpy as np

# Matriz 4x5
matriz2 = np.arange(1, 21).reshape(4, 5)

# Sumar 10 a toda la matriz
resultado = matriz2 + 10
print(resultado)
## [[11 12 13 14 15]
##  [16 17 18 19 20]
##  [21 22 23 24 25]
##  [26 27 28 29 30]]
import numpy as np

# Matriz 4x5
matriz2 = np.arange(1, 21).reshape(4, 5)

# Elevar todos los elementos al cuadrado
resultado = matriz2 ** 2
print(resultado)
## [[  1   4   9  16  25]
##  [ 36  49  64  81 100]
##  [121 144 169 196 225]
##  [256 289 324 361 400]]
import numpy as np

# Crear matriz 4x3 (R: 1:12, nrow=4)
matriz1 = np.arange(1, 13).reshape(4, 3)
print(matriz1)
## [[ 1  2  3]
##  [ 4  5  6]
##  [ 7  8  9]
##  [10 11 12]]
import numpy as np

# Crear matriz 3x4 (R: 13:24, nrow=3)
matriz2 = np.arange(13, 25).reshape(3, 4)
print(matriz2)
## [[13 14 15 16]
##  [17 18 19 20]
##  [21 22 23 24]]
import numpy as np

# Matriz1: 4x3
matriz1 = np.arange(1, 13).reshape(4, 3)

# Matriz2: 3x4
matriz2 = np.arange(13, 25).reshape(3, 4)

# Multiplicación matricial
resultado = matriz1 @ matriz2  
print(resultado)
## [[110 116 122 128]
##  [263 278 293 308]
##  [416 440 464 488]
##  [569 602 635 668]]

Data frame

import pandas as pd
import numpy as np

# Crear un array de 1 a 16 y darle forma 4x4
arr = np.arange(1, 17).reshape(4, 4)

# Convertirlo en DataFrame
df = pd.DataFrame(arr, columns=['X1', 'X2', 'X3', 'X4'])

print(df)
##    X1  X2  X3  X4
## 0   1   2   3   4
## 1   5   6   7   8
## 2   9  10  11  12
## 3  13  14  15  16
#lo usamos para instalar pandas
import sys
print(sys.executable)
## C:\Users\Jamir\AppData\Local\R\cache\R\RETICU~1\uv\cache\ARCHIV~1\WGV1EW~1\Scripts\python.exe
import pandas as pd
import numpy as np

df = pd.DataFrame({
    'nombre': ['Maryorie', 'Jorge'],
    'edad': [20, 22]
})

print(df)
##      nombre  edad
## 0  Maryorie    20
## 1     Jorge    22
import pandas as pd

# URL del CSV en GitHub
url = "https://raw.githubusercontent.com/jamirmanama-lab/BASE-DE-DATOS-EJEMPLOS/refs/heads/main/Precios%20de%20Clorhidrato.csv"

# Leer el CSV
df = pd.read_csv(url, sep=';', encoding='utf-8')

# Mostrar las primeras filas
print(df.head())
##                          ZEI Enero\r\n(2020)  ... Noviembre (2023) Diciembre (2023)
## 0                      VRAEM       5,922.26   ...        5,760.45         5,550.63 
## 1            Triple Frontera       5,147.00   ...        8,260.41         8,432.60 
## 2              Sur Amazónico       9,423.94   ...        7,314.86         7,430.54 
## 3  La Convención - Kosñipata       3,684.96   ...        4,555.65         4,714.92 
## 4                   Huallaga       5,026.14   ...        3,231.31         3,208.77 
## 
## [5 rows x 47 columns]
import pandas as pd

# Ruta del archivo CSV descargado de Kaggle
ruta = "C:/Users/Jamir/Downloads/ncr_ride_bookings.csv"

# Leer el CSV
df = pd.read_csv(ruta, sep=',', encoding='utf-8')

# Mostrar las primeras filas
print(df.head())
##          Date      Time  ... Customer Rating Payment Method
## 0  2024-03-23  12:29:38  ...             NaN            NaN
## 1  2024-11-29  18:01:39  ...             NaN            UPI
## 2  2024-08-23  08:56:10  ...             4.9     Debit Card
## 3  2024-10-21  17:17:25  ...             5.0            UPI
## 4  2024-09-16  22:08:00  ...             4.3            UPI
## 
## [5 rows x 21 columns]
import pandas as pd

# Ruta del CSV
ruta = "C:/Users/Jamir/Downloads/ncr_ride_bookings.csv"

# Leer CSV correctamente
df = pd.read_csv(ruta, sep=',', encoding='utf-8', quotechar='"')

# Limpiar comillas extra en todo el DataFrame (opcional)
df = df.applymap(lambda x: x.strip('"') if isinstance(x, str) else x)
## <string>:3: FutureWarning: DataFrame.applymap has been deprecated. Use DataFrame.map instead.
# Mostrar primeras filas
print(df.head())
##          Date      Time  ... Customer Rating Payment Method
## 0  2024-03-23  12:29:38  ...             NaN            NaN
## 1  2024-11-29  18:01:39  ...             NaN            UPI
## 2  2024-08-23  08:56:10  ...             4.9     Debit Card
## 3  2024-10-21  17:17:25  ...             5.0            UPI
## 4  2024-09-16  22:08:00  ...             4.3            UPI
## 
## [5 rows x 21 columns]