[R] Logical vectors

Joshua Wiley jwiley.psych at gmail.com
Thu Nov 4 07:46:15 CET 2010


On Wed, Nov 3, 2010 at 10:50 PM, Stephen Liu <satimis at yahoo.com> wrote:
> Hi folks,
>
> Pls help me to understand follow;
>
> An Introduction to R
>
> 2.4 Logical vectors
> http://cran.r-project.org/doc/manuals/R-intro.html#R-and-statistics
>
> 1)
>> x
> [1] 1 2 3 4 5

a vector, x, is defined with 5 elements, {1, 2, 3, 4, 5}

>> temp <- x != 1

perform the logical test that x does not equal 1 returning either TRUE or FALSE.

1 = 1 so TRUE, 2 != 1 so FALSE, etc.  next we assign *the results* of
the logical test to the vector 'temp'

>> temp
> [1] FALSE  TRUE  TRUE  TRUE  TRUE

print the vector to screen

>>
>
>
> 2)
>> x
> [1] 1 2 3 4 5

note that x has not changed here, we assigned to temp, not to x.

>> temp <- x > 1

now we assign the results of the logical test, x > 1

{1 = 1 so FALSE, 2 > 1 so TRUE, 3 > 1 so TRUE, 4 > 1 so TRUE, 5 > 1 so TRUE}

we assign these results to a vector, 'temp'.  This *new* assignment
overwrites the old vector 'temp'

>> temp
> [1] FALSE  TRUE  TRUE  TRUE  TRUE

print temp to screen, this is the results of our second logical test (x > 1).

>
>
> Why NOT
>> temp
> [1] TRUE  FALSE  FALSE FALSE  FALSE

My best guess of where you got confused is that we assigned the
results to 'temp', so 'x' remained unchanged {1, 2, 3, 4, 5}, or that
you confused '<-' which is the assignment operator in R, to "less than
negative..." *OR*  "less than or equal".  We could write this
equivalently:

> 1:5 > 1
[1] FALSE  TRUE  TRUE  TRUE  TRUE

this was the logical test, whose results were assigned to the vector, "temp".

> assign(x = "temp", value = 1:5 > 1)

using the assign function (not often recommended) to avoid any
confusion with the assignment operator, "<-".

> temp
[1] FALSE  TRUE  TRUE  TRUE  TRUE

print to screen

HTH,

Josh

>
> ?
>
>
> TIA
>
> B.R.
> Stephen L
>
>
>
> ______________________________________________
> R-help at 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.



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list