เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

การใช้ตัวแปรแบบ scoped ของ replace_with_na

เพื่อลดการเขียนโค้ดซ้ำเมื่อต้องการแทนที่ค่าด้วย NA ให้ใช้ "scoped variants" ของ replace_with_na():

  • replace_with_na_at()
  • replace_with_na_if()
  • replace_with_na_all()

รูปแบบการแทนที่มีดังนี้:

~.x == "N/A"

โค้ดนี้จะแทนที่ทุกกรณีที่มีค่าเท่ากับ "N/A"

~.x %in% c("N/A", "missing", "na", " ")

แทนที่ทุกกรณีที่มีค่าเป็น "N/A", "missing", "na", หรือ " "

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

การจัดการข้อมูลที่หายไปใน R

ดูคอร์ส

คำแนะนำการฝึกหัด

สำหรับชุดข้อมูล pacman ให้แทนที่ค่าพิเศษที่หายไป ได้แก่ "N/A", "missing", "na", และ " " โดย:

  • คอลัมน์ year, month, และ day ใช้ replace_with_na_at()
  • เฉพาะตัวแปรประเภท character ใช้ replace_with_na_if()
  • ตัวแปรทั้งหมด ใช้ replace_with_na_all()

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

# Use `replace_with_na_at()` to replace with NA
replace_with_na_at(pacman,
                   .vars = c(___, ___, ___), 
                   ~.x %in% c(___, ___, ___, ___))

# Use `replace_with_na_if()` to replace with NA the character values using `is.character`
replace_with_na_if(pacman,
                   .predicate = ___, 
                   ~.x %in% c(___, ___, ___, ___))

# Use `replace_with_na_all()` to replace with NA
replace_with_na_all(___, ___ %in% c(___, ___, ___, ___))
แก้ไขและรันโค้ด