forked from joanby/r-basic
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrueba1.Rmd
More file actions
128 lines (97 loc) · 2.28 KB
/
Prueba1.Rmd
File metadata and controls
128 lines (97 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
---
title: "R y Python"
author: "Daniel Barraza Marmolejo"
date: "10/16/2020"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Reticulate
```{r}
# Reticulate es una interfaz en R para usar módulos, clases, funciones de Python
library(reticulate)
# Una librería de Python es "os" Operation System
# variable R, "import" función de reticulate, "os" librería Ptyhon
# os
os <- import("os")
#listdir función Python
os$listdir(".")
```
```{r}
#library(reticulate)
# La instalcaión de librerías se tuvo que hacer en los env r-miniconda y r-reticulate
# Porque las librerias de base, no funcionaban
#use_python("/Users/danielbarraza/opt/anaconda3/bin/python3")
#py_install("nombre del paquete a instalar")
#os <- import("os")
#os$listdir(".")
```
```{r}
source_python("add.py")
add(3,4)
```
```{r}
# Conversión de OBJETOS de un lenguaje a otro
# "np" variable de r, "import" de reticulate para importar "numpy" de python,
# a la cual le añadimos un conversor "convert" por defecto la variable es FALSE
# ESTO INDICA QUE NO SE VA HACER UNA CONVERSIÓN DE OBJETOS PYTHON A OBJETOS A R DIRECTA,
# sino que vamos a estar trabajando con objetos nativos de Python por comodidad.
np <- import("numpy", convert = FALSE)
# Creamos una variable "x"
x <- np$array(c(1:4))
sum <- x$cumsum()
# Objeto Python
print(sum)
# Para convertir un OBJETO Python a R
# Objeto R
py_to_r(sum)
```
## Ayuda
```{r}
# Ayuda de r
help(py_to_r)
# Ayuda de python
py_help(os$chdir)
# Desde el mismo sitio
```
## Arrays
```{r}
a <- np_array(c(1:10), dtype = "float16")
# order = "C" indica que se use el estilo de guardado en memoria de C, en lugar del
# estilo de FORTRAN, que es el que basicámente usa Python para optimizar los cálculos
# de muchos números.
#a <- np_array(c(1:10), order = "C")
a
# Se crea un objeto PYTHON desde R
```
```{r}
datos <- iris
head(datos)
datos_py <- r_to_py(datos)
```
```{python}
import numpy as np
import pandas as pd
r.datos_py.head()
```
## Sparse Matrix
```{r}
library(Matrix)
N <- 6
set.seed(123)
sparse_mat <- sparseMatrix(
i = sample(N, N, replace = F),
j = sample(N, N, replace = F),
x = runif(N),
dims = c(N, N)
)
sparse_mat
sparse_mat_py <- r_to_py(sparse_mat)
```
```{python}
r.sparse_mat_py
```
```{r}
py_to_r(sparse_mat_py)
```