ReeceGoding / Frustration-One-Year-With-R

An extremely long review of R.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

No need for `which` in assignment to subset

michaeldorman opened this issue · comments

In 3.1, result[which(result < 0.5)] <- 0 can be replaced with the simpler result[result < 0.5] <- 0

P.S. Very interesting document!

I'm surprised. I was certain that it had some relevance regarding how NA values are handled. Apparently I'm wrong.

withWhich <- withoutWhich <- c(0.1, 0.3, 0.5, 0.7, 0.9, NA)
which(withWhich < 0.5) #Returns c(1, 2)
withoutWhich < 0.5 #Returns c(TRUE, TRUE, FALSE, FALSE, FALSE, NA)
withWhich[which(withWhich < 0.5)] <- 0
withWhich #Returns c(0, 0, 0.5, 0.7, 0.9, NA)
withoutWhich[withoutWhich < 0.5] <- 0
withoutWhich #Returns c(0, 0, 0.5, 0.7, 0.9, NA)
identical(withWhich, withoutWhich) #TRUE

I'll fix it in a later version.

Fixed.