สรุป Monopoly

การเขียน R Code อย่างมีประสิทธิภาพ

Colin Gillespie

Jumping Rivers & Newcastle University

Data frame vs. Matrix

# Original
rolls <- data.frame(d1 = sample(1:6, 3, replace = TRUE),
                    d2 = sample(1:6, 3, replace = TRUE))
# Updated
rolls <- matrix(sample(1:6, 6, replace = TRUE), ncol = 2)
  • เวลารันการจำลอง Monopoly ทั้งหมด: จาก 2 วินาที เหลือ 0.5 วินาที
  • การสร้าง data frame ช้ากว่า matrix
  • ในการจำลอง Monopoly สร้าง data frame ถึง 10,000 ครั้ง
การเขียน R Code อย่างมีประสิทธิภาพ

apply vs. rowSums

# Original
total <- apply(df, 1, sum)
# Updated
total <- rowSums(df)
  • จาก 0.5 วินาที เหลือ 0.16 วินาที — เร็วขึ้น 3 เท่า
การเขียน R Code อย่างมีประสิทธิภาพ

& vs. &&

# Original
is_double[1] & is_double[2] & is_double[3]
# Updated
is_double[1] && is_double[2] && is_double[3]
  • เพิ่มความเร็วได้เล็กน้อย
  • จาก 0.16 วินาที เหลือ 0.15 วินาที
การเขียน R Code อย่างมีประสิทธิภาพ

ภาพรวม

วิธี เวลา (วินาที) เร็วขึ้น
Original 2.00 1.0
Matrix 0.50 4.0
Matrix + rowSums 0.20 10.0
Matrix + rowSums + && 0.19 10.5
การเขียน R Code อย่างมีประสิทธิภาพ

มาฝึกกันเถอะ!

การเขียน R Code อย่างมีประสิทธิภาพ

Preparing Video For Download...