# This R environment comes with all of CRAN preinstalled, as well as many other helpful packages
# The environment is defined by the kaggle/rstats docker image: https://github.com/kaggle/docker-rstats
# For example, here's several helpful packages to load in 

library(ggplot2) # Data visualization
library(readr) # CSV file I/O, e.g. the read_csv function
library(stringr)
library(dplyr)
library(data.table)
# Input data files are available in the "../input/" directory.
# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory

system("ls ../input")

product <- fread('../input/producto_tabla.csv')
uniqueN(product$NombreProducto)

ini_weight <- ifelse(grepl('(\\s[0-9]\\s[0-9]+(kg|g|Kg))', product$NombreProducto) == T, str_trim(str_extract(product$NombreProducto, '(\\s[0-9]\\s[0-9]+(kg|g|Kg))'), side = 'both'), str_extract(product$NombreProducto, '\\d+(g|Kg|kg)'))
sec_weight <- str_replace(ini_weight, ' ', '.')
weight <- ifelse(is.na(str_match(sec_weight, "Kg|kg")), as.numeric(str_extract(sec_weight, '\\d+')), ifelse(is.na(str_match(sec_weight, '\\.')), as.numeric(str_extract(sec_weight, '\\d+'))*1000, as.numeric(str_extract(sec_weight, '\\d.\\d+'))*1000))

product <- cbind(product, weight) %>% rename(weight = V1)
product$NombreProducto <- str_replace_all(product$NombreProducto, '(\\s[0-9]\\s[0-9]+(kg|g|Kg))', '')
product$NombreProducto <- str_replace_all(product$NombreProducto, '(\\s[0-9]\\w+)', '')
product$NombreProducto <- str_trim(str_replace_all(product$NombreProducto, '\\d$', ''), side = 'both')

head(product)
#str_extract(product$NombreProducto, '\\d+(g|Kg|kg)')
uniqueN(product$NombreProducto)
