In R, why is `[` better than `subset`?

Answer

scramble <-function(x) x[sample(nrow(x)),]

subscramble <-function(x, condition){
  scramble(subset(x, condition))}

subscramble(mtcars, cyl ==4)

This returns the error:

Error in eval(expr, envir, enclos) : object 'cyl' not found

because R no longer "knows" where to find the object called 'cyl'. He also points out the truly bizarre stuff that can happen if by chance there is an object called 'cyl' in the global environment:

cyl <-4
subscramble(mtcars, cyl ==4)

cyl <- sample(10,100, rep = T)
subscramble(mtcars, cyl ==4)

All r Questions

Ask your interview questions on r

Write Your comment or Questions if you want the answers on r from r Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---