#1. Kết nối vơi Spark

#system("java -version")        # Kiểm tra phiên bản Java 
#install.packages(“sparklyr”)   # Tải về gói sparklyr 
#library(sparklyr)          # Sử dụng thư viện đã được tải về 
#spark_instal()             # Khởi chạy môi trường 
#sc ← spark_connect(master = "local)    # Khởi tạo cụm trong Spark 

2.Cài đặt gói OKcupid :

#download.file("https://github.com/r-spark/okcupid/raw/master/profiles.csv.zip","okcupid.zip")
#unzip("okcupid.zip", exdir = "data")
#unlink("okcupid.zip")

Nếu máy cấu hình thấp thì ta có thể cài gói sau nhưng không khuyến khích dùng :

#profile <- read.csv("data/profiles.csv")
#head(profile)
#write.csv(dplyr::sample_n(profiles, 10^3), "data/profiles.csv", row.names = FALSE)

#3.Xử lý dữ liệu

library(sparklyr)
## 
## Attaching package: 'sparklyr'
## The following object is masked from 'package:stats':
## 
##     filter
library(ggplot2)
library(dbplot)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
sc <- spark_connect(master = "local")
okc <- spark_read_csv(sc, "data/profiles.csv",
 escape = "\"",
 memory = FALSE,
 options = list(multiline = TRUE)
) %>%
 mutate(
 height = as.numeric(height),
 income = ifelse(income == "-1", NA, as.numeric(income))
 ) %>%
 mutate(sex = ifelse(is.na(sex), "missing", sex)) %>%
 mutate(drinks = ifelse(is.na(drinks), "missing", drinks)) %>%
 mutate(drugs = ifelse(is.na(drugs), "missing", drugs)) %>%
 mutate(job = ifelse(is.na(job), "missing", job))

Kiểm tra DL bằng glimpse()

glimpse(okc)
## Rows: ??
## Columns: 31
## Database: spark_connection
## $ age         <int> 22, 35, 38, 23, 29, 29, 32, 31, 24, 37, 35, 28, 24, 30, 29…
## $ body_type   <chr> "a little extra", "average", "thin", "thin", "athletic", "…
## $ diet        <chr> "strictly anything", "mostly other", "anything", "vegetari…
## $ drinks      <chr> "socially", "often", "socially", "socially", "socially", "…
## $ drugs       <chr> "never", "sometimes", "missing", "missing", "never", "miss…
## $ education   <chr> "working on college/university", "working on space camp", …
## $ essay0      <chr> "about me:<br />\n<br />\ni would love to think that i was…
## $ essay1      <chr> "currently working as an international agent for a freight…
## $ essay2      <chr> "making people laugh.<br />\nranting about a good salting.…
## $ essay3      <chr> "the way i look. i am a six foot half asian, half caucasia…
## $ essay4      <chr> "books:<br />\nabsurdistan, the republic, of mice and men …
## $ essay5      <chr> "food.<br />\nwater.<br />\ncell phone.<br />\nshelter.", …
## $ essay6      <chr> "duality and humorous things", NA, NA, "cats and german ph…
## $ essay7      <chr> "trying to find someone to hang out with. i am down for an…
## $ essay8      <chr> "i am new to california and looking for someone to wisper …
## $ essay9      <chr> "you want to be swept off your feet!<br />\nyou are tired …
## $ ethnicity   <chr> "asian, white", "white", NA, "white", "asian, black, other…
## $ height      <dbl> 75, 70, 68, 71, 66, 67, 65, 65, 67, 65, 70, 72, 72, 66, 62…
## $ income      <dbl> NA, 80000, NA, 20000, NA, NA, NA, NA, NA, NA, NA, 40000, N…
## $ job         <chr> "transportation", "hospitality / travel", "missing", "stud…
## $ last_online <chr> "2012-06-28-20-30", "2012-06-29-21-41", "2012-06-27-09-10"…
## $ location    <chr> "south san francisco, california", "oakland, california", …
## $ offspring   <chr> "doesn&rsquo;t have kids, but might want them", "doesn&rsq…
## $ orientation <chr> "straight", "straight", "straight", "straight", "straight"…
## $ pets        <chr> "likes dogs and likes cats", "likes dogs and likes cats", …
## $ religion    <chr> "agnosticism and very serious about it", "agnosticism but …
## $ sex         <chr> "m", "m", "m", "m", "m", "m", "f", "f", "f", "m", "m", "m"…
## $ sign        <chr> "gemini", "cancer", "pisces but it doesn&rsquo;t matter", …
## $ smokes      <chr> "sometimes", "no", "no", "no", "no", "no", NA, "no", "when…
## $ speaks      <chr> "english", "english (fluently), spanish (poorly), french (…
## $ status      <chr> "single", "single", "available", "single", "single", "sing…

Thêm biến phản hồi dạng cột trong tập DL và xem phân phối của nó :

okc <- okc %>%
 mutate(not_working = ifelse(job %in% c("student", "unemployed", "retired"), 1 , 0)
 )
okc %>%
 group_by(not_working) %>%
 tally()
## # Source: spark<?> [?? x 2]
##   not_working     n
##         <dbl> <dbl>
## 1           0 54541
## 2           1  5405

phân tách DL bằng cách sử dụng hàm sdf_random_split() :

data_split <- sdf_random_split(okc,traning = 0.8, testing = 0.2, seed = 42)
okc_train <- data_split$traning
okc_test <- data_split$testing

Ta có thể xem phân phối biến phản hồi của mình :

okc_train %>% 
  group_by(not_working) %>% 
  tally %>% 
  mutate(frac = n/sum(n),na.rm = TRUE)
## Warning: Missing values are always removed in SQL aggregation functions.
## Use `na.rm = TRUE` to silence this warning
## This warning is displayed once every 8 hours.
## # Source: spark<?> [?? x 4]
##   not_working     n   frac na.rm
##         <dbl> <dbl>  <dbl> <lgl>
## 1           0 43526 0.910  TRUE 
## 2           1  4306 0.0900 TRUE

Sử dụng hàm sdf_describe(), ta có thể thu được summarises() bằng số của tất cả các cột cụ thể :

sdf_describe(okc_train,cols = c("age","income"))
## # Source: spark<?> [?? x 3]
##   summary age                income           
##   <chr>   <chr>              <chr>            
## 1 count   47832              9148             
## 2 mean    32.289534203043985 103015.9597726279
## 3 stddev  9.435583525925374  199557.2035173403
## 4 min     18                 20000.0          
## 5 max     110                1000000.0

ta có thể sử dụng dbplot để vẽ biểu đồ :

dbplot_histogram(okc_train,age)

Ví dụ : Chúng ra có thể khám phá biến tôn giáo :

prop_data <- okc_train %>%
 mutate(religion = regexp_extract(religion, "^\\\\w+", 0)) %>%
 group_by(religion, not_working) %>%
 tally() %>%
 group_by(religion) %>%
 summarise(
 count = sum(n),
 prop = sum(not_working * n) / sum(n)
 ) %>%
 mutate(se = sqrt(prop * (1 - prop) / count)) %>%
 collect()
prop_data
## # A tibble: 10 × 4
##    religion     count   prop      se
##    <chr>        <dbl>  <dbl>   <dbl>
##  1 christianity  4616 0.121  0.00480
##  2 atheism       5570 0.117  0.00436
##  3 judaism       2463 0.0739 0.00529
##  4 other         6166 0.0837 0.00346
##  5 hinduism       371 0.0970 0.0154 
##  6 <NA>         16087 0.0718 0.002  
##  7 agnosticism   7048 0.0988 0.00361
##  8 catholicism   3825 0.0907 0.00469
##  9 islam          116 0.181  0.0357 
## 10 buddhism      1570 0.0924 0.00728

Lưu ý rằng là prop_data là một DataFrame nhỏ đã được thu thập vào bộ nhớ trong R, ta có thể tận dụng lợi thế của ggplot2 để thực quan hoá DL :

prop_data %>%
 ggplot(aes(x = religion, y = prop)) + geom_point(size = 2) +
 geom_errorbar(aes(ymin = prop - 1.96 * se, ymax = prop + 1.96 * se),
 width = .1) +
 geom_hline(yintercept = sum(prop_data$prop * prop_data$count) /
 sum(prop_data$count))