การตั้งชื่อเมทริกซ์
เพื่อให้จำได้ว่า star_wars_matrix เก็บข้อมูลอะไรไว้ ลองเพิ่มชื่อภาพยนตร์ให้กับแถวต่าง ๆ ของเมทริกซ์ ซึ่งไม่เพียงช่วยให้อ่านข้อมูลได้ง่ายขึ้น แต่ยังเป็นประโยชน์เมื่อต้องการเลือกองค์ประกอบเฉพาะออกมาจากเมทริกซ์อีกด้วย
เช่นเดียวกับเวกเตอร์ สามารถเพิ่มชื่อให้กับแถวและคอลัมน์ของเมทริกซ์ได้ดังนี้
rownames(my_matrix) <- row_names_vector
colnames(my_matrix) <- col_names_vector
ได้เตรียมเวกเตอร์สองตัวไว้ให้แล้ว ได้แก่ region และ titles ซึ่งจะใช้ตั้งชื่อคอลัมน์และแถวของ star_wars_matrix ตามลำดับ
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
R เบื้องต้น
คำแนะนำการฝึกหัด
- ใช้
colnames()เพื่อตั้งชื่อคอลัมน์ของstar_wars_matrixด้วยเวกเตอร์region - ใช้
rownames()เพื่อตั้งชื่อแถวของstar_wars_matrixด้วยเวกเตอร์titles - แสดงผล
star_wars_matrixเพื่อดูผลลัพธ์ที่ได้
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Box office Star Wars (in millions!)
new_hope <- c(460.998, 314.4)
empire_strikes <- c(290.475, 247.900)
return_jedi <- c(309.306, 165.8)
# Construct matrix
star_wars_matrix <- matrix(c(new_hope, empire_strikes, return_jedi), nrow = 3, byrow = TRUE)
# Vectors region and titles, used for naming
region <- c("US", "non-US")
titles <- c("A New Hope", "The Empire Strikes Back", "Return of the Jedi")
# Name the columns with region
# Name the rows with titles
# Print out star_wars_matrix