← Back to R Course | Chapter 12: Best Practices | Lesson 3 of 6

which() बनाम subset()

which और subset दोनों एक rule match करने वाली चीज़ें ढूंढते हैं, लेकिन which आपको positions देता है जबकि subset actual rows देता है। यह seat numbers माँगने बनाम लोगों को माँगने जैसा है।
Syntax
r
vector_name[which(condition)]
subset(df, condition)

which() बनाम subset()

which() एक condition match करने वाली indices return करता है और किसी भी vector पर काम करता है, जबकि subset() specifically column names directly इस्तेमाल करते हुए एक data frame की rows filter करने के लिए है।

Basic filtering के लिए df[which(df$col > x), ] या simpler df[df$col > x, ] इस्तेमाल करें, और जब आप एक साथ specific columns भी select करना चाहें subset() के लिए reach करें। दोनों slightly different syntax और use cases के साथ same filtering intent express करते हैं।

Note:
  • एक plain vector के लिए, which() इस्तेमाल करें।
  • एक data frame की rows filter करने के लिए, subset() या direct df[condition, ] indexing ज़्यादा idiomatic है।

उदाहरण: which() vs subset()

markup
df <- data.frame(name = c("Alice", "Bob", "Cara"), age = c(30, 25, 40))

cat("Using which():\n")
print(df[which(df$age > 28), ])

cat("Using subset():\n")
print(subset(df, age > 28))
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. data में NA के साथ which() इस्तेमाल करना और NA rows के appear होने की उम्मीद करना, जब वे drop हो जाती हैं।
  2. programming code में subset() इस्तेमाल करना और unexpected results पाना, जब यह columns को एक special तरीके से evaluate करता है।
  3. यह उम्मीद करना कि which(df$age > 28) rows return करेगा, जब यह positions return करता है जिन्हें df[..., ] की तरह इस्तेमाल करना ज़रूरी है।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.