ปัญหา
ฉันต้องการทดสอบว่ามีองค์ประกอบของรายการอยู่หรือไม่นี่คือตัวอย่าง
foo <- list(a=1)
exists('foo')
TRUE #foo does exist
exists('foo$a')
FALSE #suggests that foo$a does not exist
foo$a
[1] 1 #but it does exist
ในตัวอย่างนี้ฉันรู้ว่าfoo$aมีอยู่ แต่การทดสอบกลับFALSEมา
ฉันมองเข้าไป?existsและพบว่าwith(foo, exists('a')ผลตอบแทนTRUEนั้น แต่ไม่เข้าใจว่าทำไมถึงexists('foo$a')กลับFALSEมา
คำถาม
- จะ
exists('foo$a')กลับมาทำไมFALSE? - ใช้
with(...)แนวทางที่ต้องการหรือไม่?
foo <- list(a1=1)
!is.null(foo$a)(หรือ!is.null(foo[["a"]])จะปลอดภัย)? (หรือexists("a",where=foo))