survey <- data.frame(
id = 1:8,
grade = factor(c("碩一", "碩二", "碩一", "碩二",
"碩一", "碩二", "碩一", "碩二")),
hours = c("3", "5", "0", "10", "不確定", "2", "8", "4"),
score = factor(c(70, 85, 56, 92, 88, 60, 56, 78))
)
str(survey)
## 'data.frame': 8 obs. of 4 variables:
## $ id : int 1 2 3 4 5 6 7 8
## $ grade: Factor w/ 2 levels "碩一","碩二": 1 2 1 2 1 2 1 2
## $ hours: chr "3" "5" "0" "10" ...
## $ score: Factor w/ 7 levels "56","60","70",..: 3 5 1 7 6 2 1 4
第一題:
id是integer(整數型)、grade有兩個levels是factor(字串型)。
型態不合理的是hours和score,因為前者出現了「不確定」的數值導致原本應為數值型的樣態變成字串型;score本來代表「分數」,也應該是numeric,但在建立資料的時候確實用factor(),所以現在被當成類別資料。
mean_score <- mean(as.numeric(survey$score))
mean_hours <- mean(as.numeric(survey$hours))
cat("平均分數", mean_score, "\n")
cat("平均時數", mean_hours, "\n")
score_num <- as.numeric(as.character(survey$score))
hours_num <- as.numeric(survey$hours)
## Warning: NAs introduced by coercion
mean_score <- mean(score_num)
mean_hours <- mean(hours_num, na.rm = TRUE)
cat("平均分數", mean_score, "\n")
## 平均分數 73.125
cat("平均時數", mean_hours, "\n")
## 平均時數 4.571429
第二題:
2.1:會列出「Warning in mean(as.numeric(survey$hours)) : NAs introduced by coercion平均分數 3.625;平均時數 NA 」
2.2-4:mean_score 跑出 3.625,而 mean_hours 得出 NA。mean_score 出錯是因為 score 是 factor型態,所以直接使用 as.numeric() 會取得 factor 的內部編碼,而不是原本的分數,因此算出的 3.625 並非真正的平均分數。應先用 as.character() 取回原始數值,再轉為 numeric。
包含「不確定」 出錯則是hours 出錯的原因,包含文字無法轉換為 numeric,因此被轉成 NA。mean() 預設不會忽略 NA,所以最後結果也是 NA。可以使用 na.rm = TRUE 排除缺失值。
最終修正後平均分數為 73.125,平均時數約為 4.571。我使用 str() 檢查資料型態、直接查看轉換後的資料值,並使用 summary() 檢查數值範圍與缺失值,確認轉換與計算結果合理。
第三題:
3.1 :分數大於 75 的是第2、4、5、8個
3.2 :碩一 67.50分 碩二 78.75分
3.3:1個缺漏值
survey$id[score_num > 75]
## [1] 2 4 5 8
tapply(score_num, survey$grade, mean)
## 碩一 碩二
## 67.50 78.75
sum(is.na(hours_num))
## [1] 1
第四題
對話一
{r hw-ai, eval=FALSE} mean_score <- mean(as.numeric(survey\(score))mean_hours <- mean(as.numeric(survey\)hours))
cat(“平均分數”, mean_score, “”) cat(“平均時數”, mean_hours, “”)
檢查不合理的地方,改好平均數
對話二
{r hw-ai, eval=FALSE} mean_score <- mean(as.numeric(survey$score)) mean_hours <- mean(as.numeric(survey$hours)) cat(“平均分數”, mean_score, “\n”) cat(“平均時數”, mean_hours, “\n”) 我想知道找出大於75分的id、碩一與碩二的平均分數各是多少以及找出hours的遺漏值