> -----Original Message----- > From: r-help-boun...@r-project.org > [mailto:r-help-boun...@r-project.org] On Behalf Of > soeren.vo...@eawag.ch > Sent: Friday, November 13, 2009 12:24 PM > To: r-help@r-project.org > Subject: [R] when use which() > > Hello: > > # some code to assign with and without "which" > q <- 1:20; q[c(9, 12, 14)] <- NA > r <- 1:20; r[c(8:9, 12:15)] <- NA > s <- 1:20; s[c(8:9, 12:15)] <- NA > r[q < 16] <- 0 > s[which(q < 16)] <- 0 > r;s # both: 0 0 0 0 0 0 0 0 NA 0 0 NA 0 NA 0 16 17 18 19 20 > r <- 1:20; r[c(8:9, 12:15)] <- NA > s <- 1:20; s[c(8:9, 12:15)] <- NA > r[is.na(q)] <- 30 > s[which(is.na(q))] <- 30 > r;s # both: 1 2 3 4 5 6 7 NA 30 10 11 30 NA 30 NA 16 17 18 19 20 > > So it appears to me that "a[b] <- c" delivers the same results as > a[which(b)] <- c". Is there any situation where the assignment with/ > out which indeed makes a difference?
When using "[" there should be no difference between using x[condition] and x[which(condition)]. which() is just a waste of typing, cpu time, and memory there. If you want all x that don't satisfy the condition x[!condition] works but x[-which(condition)] silently gives the wrong answer when all(condition==FALSE). There is one weird case, in [[, not [, where there is a difference, and this might be considered a bug: > list(a=10,b=20,c=30)[[c(FALSE,TRUE,FALSE)]] Error in list(a = 10, b = 20, c = 30)[[c(FALSE, TRUE, FALSE)]] : attempt to select less than one element > list(a=10,b=20,c=30)[[which(c(FALSE,TRUE,FALSE))]] [1] 20 [[ is treating the vector of logicals as a vector of integers and it can only work if all of them are TRUE and the list has at least 3 levels of recursion > list(list(list(10,20),list(30,40)))[[c(TRUE,TRUE,TRUE)]] [1] 10 Of course, someone can write a package that defines a method for [ that doesn't work this way, but that would be unfriendly. Bill Dunlap Spotfire, TIBCO Software wdunlap tibco.com > > Thanks for help > > Regards > > Sören > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. > ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.