[R] For logical i and length(i) > length(x), x[i] <- value makes length(x) == length(i)

Suharto Anggono Suharto Anggono suharto_anggono at yahoo.com
Sat Sep 5 19:02:05 CEST 2015

I came across this behavior when I followed the code of function 'rank' in R.

It seems that subassignment of a vector by a logical index vector that is longer than the original vector always results in expanding the original vector to the length of the index vector.

The resulting length may be different from the result of subassignment by the equivalent numeric vector. For subassignment of a vector by a numeric index vector, the original vector is expanded to the maximum index, if it is larger than the length of the original vector.

This is an example.

> x <- NA
> x[c(FALSE,TRUE,FALSE)] <- 1
> x
[1] NA  1 NA

Compare to this.

> x <- NA
> x[which(c(FALSE,TRUE,FALSE))] <- 1
> x
[1] NA  1

Does S exhibit the same behavior?

Currently, if there is NA and na.last = "keep", function 'rank' in R relies on this behavior to give correct result length.

In "R Language Definition", "3.4.1 Indexing by vectors" says: "Logical. The indexing i should generally have the same length as x. .... If it is longer, then x is conceptually extended with NAs. ...." The statement can be taught to support the observed behavior.

> sessionInfo()
R version 3.2.2 (2015-08-14)
Platform: i386-w64-mingw32/i386 (32-bit)
Running under: Windows XP (build 2600) Service Pack 2

[1] LC_COLLATE=English_United States.1252
[2] LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

More information about the R-help mailing list