R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

summary(cars)
##      speed           dist       
##  Min.   : 4.0   Min.   :  2.00  
##  1st Qu.:12.0   1st Qu.: 26.00  
##  Median :15.0   Median : 36.00  
##  Mean   :15.4   Mean   : 42.98  
##  3rd Qu.:19.0   3rd Qu.: 56.00  
##  Max.   :25.0   Max.   :120.00

Including Plots

You can also embed plots, for example:

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.

練習一

用 read_csv() 讀進 data/michelin_2026.csv,存成 mic26,然後回答。

  • 幾列幾欄
  • 每一欄是什麼型態
  • Award 有哪幾類,各幾家
library(readr)
library(dplyr)
## Warning: package 'dplyr' was built under R version 4.5.2
## 
## 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
mic26 <- read_csv(
  "/Users/tsaipeitzu/Desktop/wh/michelin_2026.csv",
  show_col_types = FALSE
)

dim(mic26)
## [1] 19622    14
str(mic26)
## spc_tbl_ [19,622 × 14] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
##  $ Name                 : chr [1:19622] "8 1/2 Otto e Mezzo - Bombana" "ABaC" "AM par Alexandre Mazzia" "Addison" ...
##  $ Address              : chr [1:19622] "Shop 202, 2F, Alexandra House, 18 Chater Road, Central, Hong Kong, Hong Kong SAR China" "Avenida del Tibidabo 1, Barcelona, 08022, Spain" "9 rue François-Rocca, Marseille, 13008, France" "Fairmont Grand Del Mar, 5200 Grand Del Mar Way, San Diego, CA, 92130, USA" ...
##  $ Location             : chr [1:19622] "Hong Kong, Hong Kong SAR China" "Barcelona, Spain" "Marseille, France" "San Diego, CA, USA" ...
##  $ Price                : chr [1:19622] "$$$$" "$$$$" "$$$$" "$$$$" ...
##  $ Cuisine              : chr [1:19622] "Italian" "Creative" "Creative" "Contemporary" ...
##  $ Longitude            : num [1:19622] 114.16 2.14 5.39 -117.2 -2.04 ...
##  $ Latitude             : num [1:19622] 22.3 41.4 43.3 32.9 43.3 ...
##  $ PhoneNumber          : num [1:19622] 8.52e+10 3.49e+10 3.35e+10 1.86e+10 3.49e+10 ...
##  $ Url                  : chr [1:19622] "https://guide.michelin.com/en/hong-kong-region/hong-kong/restaurant/8%C2%BD-otto-e-mezzo-bombana" "https://guide.michelin.com/en/catalunya/barcelona/restaurant/abac" "https://guide.michelin.com/en/provence-alpes-cote-dazur/marseille/restaurant/am-par-alexandre-mazzia" "https://guide.michelin.com/en/california/us-san-diego/restaurant/addison" ...
##  $ WebsiteUrl           : chr [1:19622] "https://www.ottoemezzobombana.com" "https://abacrestaurant.com" "https://www.alexandre-mazzia.com/" "https://www.addisondelmar.com/" ...
##  $ Award                : chr [1:19622] "3 Stars" "3 Stars" "3 Stars" "3 Stars" ...
##  $ GreenStar            : num [1:19622] 0 0 0 0 0 0 0 0 1 1 ...
##  $ FacilitiesAndServices: chr [1:19622] "Air conditioning,Car park,Interesting wine list,Valet parking,Wheelchair access" "Air conditioning,Interesting wine list,Terrace" "Air conditioning,Interesting wine list,Pets allowed everywhere" "Air conditioning,Car park,Garden or park,Interesting wine list,Terrace,Valet parking,Wheelchair access" ...
##  $ Description          : chr [1:19622] "(The restaurant is temporarily closed.) Owner-chef Umberto Bombana’s restaurant, which oozes Italian charm and "| __truncated__ "Tradition, cutting-edge, flavour, attitude and passion, along with a consistent approach, define to perfection "| __truncated__ "In his eatery near the Stade Vélodrome, this artist-cum-chef on a perpetual creative quest has elevated the sma"| __truncated__ "Global inspiration and Californian sentimentality are at the heart of Chef William Bradley’s world-class dining"| __truncated__ ...
##  - attr(*, "spec")=
##   .. cols(
##   ..   Name = col_character(),
##   ..   Address = col_character(),
##   ..   Location = col_character(),
##   ..   Price = col_character(),
##   ..   Cuisine = col_character(),
##   ..   Longitude = col_double(),
##   ..   Latitude = col_double(),
##   ..   PhoneNumber = col_double(),
##   ..   Url = col_character(),
##   ..   WebsiteUrl = col_character(),
##   ..   Award = col_character(),
##   ..   GreenStar = col_double(),
##   ..   FacilitiesAndServices = col_character(),
##   ..   Description = col_character()
##   .. )
##  - attr(*, "problems")=<externalptr>
mic26 %>%
  count(Award)
## # A tibble: 5 × 2
##   Award                    n
##   <chr>                <int>
## 1 1 Star                3181
## 2 2 Stars                547
## 3 3 Stars                162
## 4 Bib Gourmand          3743
## 5 Selected Restaurants 11989

練習二

用 d 回答。

  1. 把統獨立場 tondu 轉成有順序的 factor,從「儘快統一」到「儘快宣布獨立」
  2. 用 count() 確認轉換前後每一類的人數一樣
  3. 各統獨立場的平均威脅感是多少

選項的原文與順序是「儘快統一」、「維持現狀,以後走向統一」、「維持現狀,看情形再決定獨立或統一」、「永遠維持現狀」、「維持現狀,以後走向獨立」、「儘快宣布獨立」。

library(tidyverse)
## Warning: package 'ggplot2' was built under R version 4.5.2
## Warning: package 'tidyr' was built under R version 4.5.2
## Warning: package 'purrr' was built under R version 4.5.2
## Warning: package 'lubridate' was built under R version 4.5.2
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ forcats   1.0.1     ✔ stringr   1.5.2
## ✔ ggplot2   4.0.2     ✔ tibble    3.3.0
## ✔ lubridate 1.9.5     ✔ tidyr     1.3.2
## ✔ purrr     1.2.1     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
# 1. 正確讀入原始問卷
survey <- read_csv(
  "w4_survey_raw.csv",
  show_col_types = FALSE,
  name_repair = "unique_quiet"
) %>%
  slice(-(1:2)) %>%
  type_convert(guess_integer = FALSE) %>%
  rename(
    consent = `Q1...15`,
    screen = `Q1...16`
  )
## 
## ── Column specification ────────────────────────────────────────────────────────
## cols(
##   .default = col_character(),
##   StartDate = col_datetime(format = ""),
##   EndDate = col_datetime(format = ""),
##   Progress = col_double(),
##   `Duration (in seconds)` = col_double(),
##   Finished = col_logical(),
##   RecordedDate = col_datetime(format = ""),
##   RecipientLastName = col_logical(),
##   RecipientFirstName = col_logical(),
##   RecipientEmail = col_logical(),
##   ExternalReference = col_logical(),
##   Q1_DO_1 = col_double(),
##   Q1_DO_2 = col_double(),
##   Q1_DO_3 = col_double(),
##   Q1_DO_4 = col_double(),
##   Q5_1 = col_double(),
##   Q14_1 = col_double(),
##   Q15_1 = col_double(),
##   Q34 = col_double(),
##   Q34_DO_1 = col_double(),
##   Q34_DO_2 = col_double()
##   # ... with 19 more columns
## )
## ℹ Use `spec()` for the full column specifications.
# 2. 選出需要的欄位
svy <- survey %>%
  select(
    ResponseId, Finished, `Duration (in seconds)`,
    consent, screen, Q2,
    gender = Q3, birth = Q5_1, edu = Q6, income = Q7,
    us_defend = Q14_1, resist = Q15_1,
    starts_with("Q22_"), -starts_with("Q22_DO"),
    threat = Q25_1, party = Q25, pid = Q24,
    pid_other = Q24_7_TEXT,
    tondu = Q27, identity = Q26,
    r1_ct1_attrname,
    starts_with("China_Vignette")
  )

# 3. 建立 748 人的分析樣本 d
d <- svy %>%
  filter(
    consent == "同意",
    screen == "無需當兵",
    !is.na(r1_ct1_attrname)
  )

# 4. 把 threat 正確轉成數字
d <- d %>%
  mutate(
    threat = parse_number(threat)
  )
d <- svy %>%
  filter(consent == "同意",
         screen == "無需當兵",
         !is.na(r1_ct1_attrname))
nrow(d)
## [1] 748
library(dplyr)

# 1. 先看轉換前各類人數
d %>%
  count(tondu)
## # A tibble: 7 × 2
##   tondu                                n
##   <chr>                            <int>
## 1 儘快宣布獨立                        27
## 2 儘快統一                             6
## 3 永遠維持現狀                       219
## 4 維持現狀,以後走向獨立             227
## 5 維持現狀,以後走向統一              46
## 6 維持現狀,看情形再決定獨立或統一   176
## 7 <NA>                                47
# 2. 把 tondu 轉成有順序的 factor
d <- d %>%
  mutate(
    tondu = factor(
      tondu,
      levels = c(
        "儘快統一",
        "維持現狀,以後走向統一",
        "維持現狀,看情形再決定獨立或統一",
        "永遠維持現狀",
        "維持現狀,以後走向獨立",
        "儘快宣布獨立"
      ),
      ordered = TRUE
    ),
    threat = as.numeric(as.character(threat))
  )
## Warning: There was 1 warning in `mutate()`.
## ℹ In argument: `threat = as.numeric(as.character(threat))`.
## Caused by warning:
## ! NAs introduced by coercion
# 3. 確認轉換後各類人數
d %>%
  count(tondu)
## # A tibble: 7 × 2
##   tondu                                n
##   <ord>                            <int>
## 1 儘快統一                             6
## 2 維持現狀,以後走向統一              46
## 3 維持現狀,看情形再決定獨立或統一   176
## 4 永遠維持現狀                       219
## 5 維持現狀,以後走向獨立             227
## 6 儘快宣布獨立                        27
## 7 <NA>                                47
# 4. 各統獨立場的平均威脅感
d %>%
  group_by(tondu) %>%
  summarise(
    mean_threat = mean(threat, na.rm = TRUE)
  )
## # A tibble: 7 × 2
##   tondu                            mean_threat
##   <ord>                                  <dbl>
## 1 儘快統一                                7.33
## 2 維持現狀,以後走向統一                  6.15
## 3 維持現狀,看情形再決定獨立或統一        6.90
## 4 永遠維持現狀                            6.68
## 5 維持現狀,以後走向獨立                  7.08
## 6 儘快宣布獨立                            7.44
## 7 <NA>                                  NaN