<jupyter_start><jupyter_text>Juntando R y Python<jupyter_code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Adicionar este bloque
#set R_HOME dynamically
import os
os.environ['R_HOME'] = r'C:\Program Files\R\R-3.6.3' # Ruta de R. Esto cambia segun el PC
#set R bin
os.environ['path'] += r';C:\Program Files\R\R-3.6.3\bin\x64;' # Ruta de R adicionando \bin\x64. Esto cambia segun el PC
import rpy2.robjects as ro
import rpy2.robjects.numpy2ri
rpy2.robjects.numpy2ri.activate()
codigo_r = """
saludar <- function(cadena){
    return(paste("Hola, ", cadena))
}
"""
ro.r(codigo_r)
saludar_py = ro.globalenv["saludar"]
res = saludar_py("<NAME>")
res[0]
type(res)
print(saludar_py.r_repr())
var_from_python = ro.FloatVector(np.arange(1,5,0.1))
var_from_python
print(var_from_python.r_repr())
ro.globalenv["var_to_r"] = var_from_python
ro.r("var_to_r")
ro.r("sum(var_to_r)")
ro.r("mean(var_to_r)")
ro.r("sd(var_to_r)")
np.sum(var_from_python)
np.mean(var_from_python)
ro.r("summary(var_to_r)")
ro.r("hist(var_to_r, breaks = 4)")<jupyter_output><empty_output><jupyter_text>Trabajar de forma conjunta entre R y Python<jupyter_code>from rpy2.robjects.packages import importr
ro.r("install.packages('extRemes')")# si os falla decidle 'n' al hacer la instalación
extremes = importr("extRemes") # library(extRemes)
fevd = extremes.fevd
print(fevd.__doc__)
#data = pd.read_csv("../datasets/time/time_series.txt", # Anterior
#                   sep = "/s*", skiprows = 1, parse_dates = [[0,1]],
#                   names = ["date", "time", "wind_speed"],
#                   index_col = 0)

data = pd.read_csv("../datasets/time/time_series.txt",
                   sep = '\s+',skiprows = 1,parse_dates = [[0,1]],
                   names = ["date", "time", "wind_speed"],
                   index_col = 0)
data.head(5)
data.shape
#max_ws = data.wind_speed.groupby(pd.TimeGrouper(freq="A")).max() # Anterior
max_ws = data.wind_speed.groupby(pd.Grouper(freq="A")).max()
max_ws
max_ws.plot(kind="bar", figsize=(16,9))
result = fevd(max_ws.values, type="GEV", method = "GMLE")
print(type(result))
result.r_repr
#print(result.names)
result.names
res = result.rx("results")
#print(res[0])
res[0]
loc, scale, shape = res[0].rx("par")[0]
loc
scale
shape<jupyter_output><empty_output><jupyter_text>Función mágica para R<jupyter_code>%load_ext rpy2.ipython
help(rpy2.ipython.rmagic.RMagics.R)
%R X=c(1,4,5,7); sd(X); mean(X)
%%R
Y = c(2,4,3,9)
lm = lm(Y~X)
summary(lm)
%R -i result plot.fevd(result)
%R -i var_from_python hist(var_from_python)
ro.globalenv["result"] = result
ro.r("plot.fevd(result)") ## puede dar error y generar un objeto rpy2.rinterface.NULL<jupyter_output><empty_output><jupyter_text>Un ejemplo complejo de R, Python y Rmagic<jupyter_code>metodos = ["MLE", "GMLE", "Bayesian", "Lmoments"]
tipos = ["GEV", "Gumbel"]
for t in tipos:
    for m in metodos:
        print("Tipo de Ajuste: ", t)
        print("Método del Ajuste: ", m)
        result = fevd(max_ws.values, method = m, type = t)
        print(result.rx("results")[0])
        %R -i result plot.fevd(result)<jupyter_output>Tipo de Ajuste:  GEV
Método del Ajuste:  MLE
{'fraction_non_alphanumeric': 0.16761363636363635, 'fraction_numerical': 0.015782828282828284, 'mean_word_length': 4.579225352112676, 'pattern_counts': {'":': 0, '<': 18, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '571207', 'license': 'MIT', 'n_tokens_mistral': 1338, 'n_tokens_neox': 1312, 'n_words': 253, 'path': 'notebooks/T12 - 1 - R y Python_Py38.ipynb', 'repo_name': 'ytapasco88/python-ml-course', 'size': '3178'}