# Doubts with logical indexing and performing arithmetic with vectors

need help with this topic i.e doubts with logical indexing and performing arithmetic with vectors in R.

Hello @nishanta567,

• Logical indexing allows filtering out some values in a vector.
–> Assume we have this vector `vect <- c(5, 3, 2, 4, 8)`. We want to keep only the values greater or equal to 4.
–> We can manually create a logical vector `logical_vect <- c(TRUE, FALSE, FALSE, TRUE, TRUE)` where for each value in `vect` we will write `TRUE` if the condition is satisfied and `FALSE` otherwise.
–> Now we can index `vect` with `logical_vect` to select only the values where we have true:
``````vect <- c(5, 3, 2, 4, 8)
logical_vect <- c(TRUE, FALSE, FALSE,  TRUE,  TRUE)
selected_vect <- vect[logical_vect] #Only the first, the fourth, and the fifth indices will be selected. Output:  5 4 8
``````

We taught this notion here in our path.

• Arithmetic with vectors is what we call vectorization in R. It is a simplified and condensed syntax of for-loops. For example, `res <- c(5, 3, 2, 4, 8) + c(1, 2, 1, 2, 1) ` is equivalent to:
``````a <- c(5, 3, 2, 4, 8)
b <- c(1, 2, 1, 2, 1)

res <- c(0, 0, 0, 0, 0) # Initialisation of the output vector with 0

for ( i in 1:5) { #5 is the length of `a` and `b`
res[i] <- a[i] + b[i] #element-wise addition
}
``````

You can say nice !!

Vectorization is possible between

• vector and vector with the same length, element-wise operations is performed.
``````res <- a + b #Output  6 5 3 6 9
``````
• vector and value, the value is duplicated as many times as there are elements in the vector and element-wise operations is performed.
``````res <- a + 2 #Output   7  5  4  6 10
``````
• vector and vector with different lengths, the smaller vector is duplicated until the size of the larger vector is reached and element-wise operations is performed (a warning message may appear to ensure that you know what you are doing).
``````res <- a + c(1,2) #Equal to a + c(c(1,2),c(1,2),c(1)) Output  6 5 3 6 9
``````
• vector as vectorized function’s argument, the function is applied to each element of the vector.
``````str_pad(string = c(5, 13, 2, 14, 8), width = 2, side = "left", pad = "0") #Output  "05" "13" "02" "14" "08"
``````
• Why prefer vectorization to for-loops? Because this makes your code more compact and it is often faster than for-loops.

• All arithmetic (+,-,*,/,%%,…) and comparisons (<, <=, >, >=, !, ==,…) operators are vectorized in R.

We taught this notion here and here in our path.

Cheers,
John.

2 Likes

Thanks john for the stuff.

Hey @nishanta567, the answer was incomplete. I updated it.

1 Like