R Language: Atomic types: Logical
A LOT of R code examples focus on advanced tasks. Only a FEW focus on the basics, assuming everyone knows everything about the core concepts. Honestly, the foundations aren't as exciting to write about. But I've encountered a lot of R users who don't have a workable grasp of beginning concepts. So let's spend a bit of time building up a ground-level understanding of R.
R has six atomic data types: logical, integer, real, complex, string, character, and raw. It has six data structures: vector, list, matrix, array, data.frame, and factor.
Atomic Data Types: Logical
Let's take a quick look at logical data types. Logical data types are TRUE or FALSE. For example:
I.am.logical <- TRUE
is.logical(I.am.logical)
This code creates a vector and places one TRUE value in the vector. Notice I said "vector" instead of "variable." In R, a simple variable is called a vector because it can contain multiple values. Is that confusing? Yes. But when you learn about vectors in R, the name makes sense.
Here's how to test for the typof( ) logical. Use is.logical( ) to see if a vector is of type logical. FALSE and TRUE are logical values. False and True are NOT logical values (at least, not in R)
> is.logical(FALSE)
[1] TRUE
> is.logical(false) # FALSE, not false. TRUE, not true (or True)
Error: object 'false' not found
> is.logical(True)
Error: object 'True' not found
> is.logical(1) # 1 is an integer. Not logical
[1] FALSE
> as.numeric(TRUE) # although the inverse sort of works
[1] 1
Oh - and sometimes "1" and "0" are logical values.
领英推荐
When you have logical values, you can perform AND, OR, NAND, and NOR operations...
> TRUE & FALSE # use & for and. Caution: & is different than &&
[1] FALSE
> TRUE | FALSE # use | for or. Caution: | is different than ||
[1] TRUE
> ! FALSE # use ! for negate
[1] TRUE
Remember talking about vectors instead of variables? Here's an example of a vector with multiple logical values.
> I.am.logical <- c(TRUE,TRUE,FALSE)
> any(I.am.logical)
[1] TRUE
> all(I.am.logical)
[1] FALSE
Now try any( ) and all( ) with the multi-value vector. These are really simple tools to examine the state of a vector.
Want more? R for Data Science shows this type of stuff every week. Here's a sample...
I teach R for LinkedIn Learning. And Raspberry Pi. I just released a course on Audiobook production. And I write Science Fiction. Try them all!
Author of "Stupid Machine" and educator at LinkedIn learning
3 年Here's the next - integers. https://www.dhirubhai.net/pulse/r-language-atomic-types-integer-mark-niemann-ross
Building on the Customer Journey to drive Lifetime Value!
3 年Good and quick way to take us back to the basics! Definitely important to not overlook these things for all that newer and more vibrant R libraries provide.