Variables and Operators in R Programming

Variables and operators in R programming are very similar to many other languages I know, so I’m not going to add notes about arithmetic operators +, -, *, / or most logical operators <, >, <=, >=, etc. Not (!) and not equals (!=) are also the same as seen in other languages I use commonly. This post contains some of the more interesting takeaways while learning the basics of R programming operators.

String Concatenation

In JavaScript, Python and C#, basic string concatenation is handled with the “+” sign. There’s multiple ways to concatenate strings, but the simplest form for these languages is “+”. Not with R programming. No, here the string concatenation is handled with the paste function

firstname <- “Christopher”
lastname <- “Brotsos”
fullname <- paste(firstname, lastname)
fullname

Note that the paste function takes an optional separator argument; the default is the space character. This is very unique syntax.

Logical Or and Logical And

The basic logical or operator is the single pipe | , and the basic logical and operator is the single ampersand, &. From what I’ve currently read, the commonplace || and && also perform logical operations, but therein lies some difference around vectors or vectorization, and I’m not knowledgeable enough to create notes on this difference *yet*.

There might also be some side effects and different handling of short-circuit evaluation…not sure there yet either. I’ll revisit the differences between the single-vs-double syntax in a later post I imagine. I found this blog post that I’ll make sure I eventually understand https://stackoverflow.com/questions/6558921/boolean-operators-and.

With that out of the way, a quick sample of using the | and & is what is seen in other common languages:

r1 <- 4 < 5
r1 # TRUE
typeof(r1) # logical

r2 <- !(5 > 1)
r2 # FALSE

r1 | r2 # true (true or false)
r1 & r2 # false (true and false)

The isTRUE Function

There is a dedicated isTRUE() function in R Programming which returns logical results:

isTRUE(r1) # true
!isTRUE(r1) # false

If you’re familiar with C#, JavaScript, or Python then there’s nothing too unique with variables and operators in R programming. Though, the observations above were some interesting takeaways when reviewing the basics.



Categories: R Programming

Tags: ,

Leave a Reply

%d bloggers like this: