Attributes
มาถึงแบบฝึกหัดสุดท้ายของคอร์สแล้ว ยินดีด้วย! มาจบด้วยโจทย์ที่ไม่ยากกันเลย
Attributes คือข้อมูลเมตาเพิ่มเติมเกี่ยวกับโครงสร้างข้อมูลของคุณ ตัวอย่าง attributes ที่พบบ่อย ได้แก่ ชื่อแถวและชื่อคอลัมน์ มิติ และคลาส ใช้ฟังก์ชัน attributes() เพื่อดึงรายการ attributes ของออบเจกต์ที่ส่งเข้าไป และหากต้องการเข้าถึง attribute เฉพาะอย่าง ให้ใช้ฟังก์ชัน attr()
ตัวอย่างการสำรวจ attributes ของ cash:
attributes(cash)
$names
[1] "company" "cash_flow" "year"
$row.names
[1] 1 2 3 4 5 6 7
$class
[1] "data.frame"
attr(cash, which = "names")
[1] "company" "cash_flow" "year"
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
R เบื้องต้นสำหรับการเงิน
คำแนะนำการฝึกหัด
- กำหนด matrix
my_matrixและ factormy_factorไว้ให้แล้ว - ใช้
attributes()กับmy_matrix - ใช้
attr()กับmy_matrixเพื่อดึง attribute"dim" - ใช้
attributes()กับmy_factor
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# my_matrix and my_factor
my_matrix <- matrix(c(1,2,3,4,5,6), nrow = 2, ncol = 3)
rownames(my_matrix) <- c("Row1", "Row2")
colnames(my_matrix) <- c("Col1", "Col2", "Col3")
my_factor <- factor(c("A", "A", "B"), ordered = T, levels = c("A", "B"))
# attributes of my_matrix
# Just the dim attribute of my_matrix
# attributes of my_factor