AnyCompiler

Indexing Aur Subsetting

x[i] ek positive i ke sath us 1-based position ka element return karta hai. x[-i] kuch aisa karta hai jiska equivalent is site ki zyada tar languages mein bilkul nahi hota: ye position i ko chhod kar har element return karta hai — ek negative index ka matlab hai "exclude karo", na ke "end se count karo" jaise Python ka x[-1] karta hai. Ek logical vector jo index ki tarah istemal kiya jata hai, jaise x[x > 25], sirf wohi elements rakhta hai jahan logical vector TRUE hai — yehi selection mask pattern hai jo pichli lesson ka x > 2 set up kar raha tha. Vectors names bhi carry kar sakte hain, names() se settable, aur phir naam se bhi aur position se bhi indexed ho sakte hain.

x <- c(10, 20, 30, 40, 50)
print(x[2])
print(x[-1])
print(x[x > 25])
names(x) <- c("a", "b", "c", "d", "e")
print(x["c"])
Output
[1] 20
[1] 20 30 40 50
[1] 30 40 50
 c 
30

x[-1] ne sirf first element (10) drop kiya aur baaki sab rakh liya — is ne last element return nahi kiya jaise Python mein x[-1] karta. x[x > 25] ne vector ki apni values istemal ki ye decide karne ke liye ke uske kaunse elements rakhne hain, baghair kisi loop ke aur baghair kisi separate filter() call ke. Aur x["c"] ne ek value ko us naam se dhoonda jo aap ne assign kiya tha, naam aur value dono print karte hue, wohi two-line shape jo named lookups hamesha produce karte hain.

Ek real indexing error

Positive indices ("sirf ye rakho") aur negative indices ("ye exclude karo") opposite instructions hain, aur agar aap unhein ek single subscript mein mix karte hain to R guess karne se refuse kar deta hai ke aap ka matlab kaunsa tha. Ye wo real error hai jo R produce karta hai, ek real run se capture kiya gaya:

x <- c(10, 20, 30)
print(x[c(-1, 2)])
Output
stderr
Error in x[c(-1, 2)] : only 0's may be mixed with negative subscripts
Calls: print
Execution halted

Pichli do lessons ki warnings ke bar-aks, ye wala waqai script ko rok deta hai — R is specific combination ko ek genuine, unrecoverable mistake manta hai, silently work around karne wali cheez nahi. Aage: strings — paste, sprintf, nchar, aur substr.

Practice exercise

x <- c(1, 2, 3, 4, 5) diya gaya hai, negative index istemal kar ke x print karo jisme first element exclude ho, phir logical mask istemal kar ke sirf wo elements print karo jo 2 se greater hain.