[R] union of a list of logical values

Prof Brian Ripley ripley at stats.ox.ac.uk
Mon Jul 22 11:37:30 CEST 2013


On 22/07/2013 10:16, Liviu Andronic wrote:
> Dear all,
> How can I obtain the union of a list of logical values?

This really only makes sense for a list of logical vectors of the same 
length.  And by 'union' you seem to mean 'or'.

Two approaches

1) Make a logical matrix and use apply(m, 1, any)

2) Use Reduce(`|`, z)

>
> Consider the following:
> x <- head(iris)
> x[,c(2,4)] <- NA
> x[c(2,4),] <- NA
> # > x
> # Sepal.Length Sepal.Width Petal.Length Petal.Width Species
> # 1          5.1          NA          1.4          NA  setosa
> # 2           NA          NA           NA          NA    <NA>
> # 3          4.7          NA          1.3          NA  setosa
> # 4           NA          NA           NA          NA    <NA>
> # 5          5.0          NA          1.4          NA  setosa
> # 6          5.4          NA          1.7          NA  setosa
> z <- data.frame(!is.na(x))
> # > z
> # Sepal.Length Sepal.Width Petal.Length Petal.Width Species
> # 1         TRUE       FALSE         TRUE       FALSE    TRUE
> # 2        FALSE       FALSE        FALSE       FALSE   FALSE
> # 3         TRUE       FALSE         TRUE       FALSE    TRUE
> # 4        FALSE       FALSE        FALSE       FALSE   FALSE
> # 5         TRUE       FALSE         TRUE       FALSE    TRUE
> # 6         TRUE       FALSE         TRUE       FALSE    TRUE
>
> I did find a solution, but it seems more like a hack:
>> ##union of logical values by rows (union of list of logical values)
>> as.logical(rowSums(z))
> [1]  TRUE FALSE  TRUE FALSE  TRUE  TRUE
>> ##union of logical values by columns
>> as.logical(colSums(z))
> [1]  TRUE FALSE  TRUE FALSE  TRUE
>
> Another unusable monstrosity is as follows:
>> ##union of list of logical values
>> z[[1]] | z[[2]] | z[[3]] | z[[4]] | z[[5]]
> [1]  TRUE FALSE  TRUE FALSE  TRUE  TRUE
>
> Is there a more elegant way to approach this problem and obtain the
> above logical vectors? Regards,
> Liviu
>
>


-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list