R Program to add 3 to each element in a given vector

How to add 3 to each element in a given vector

Here we are explaining how to write an R program to add 3 to each element in a given vector. We can give one vector value to add three to each one. For the calculation of adding here, we use the plus(+) operator. Here is.na() is used for checking whether the element x is present or not if no it will return boolean value TRUE. The syntax of this function is 

is.na(x) #Where x is the elemnt to be checked
 

How to add 3 to each element in a given vector using the R Program

Given below are the steps which are used in the R program to add 3 to each element. In this R program, we accept the vector values into variables A. The result after adding 3 to each element is stored into a variable new. Finally the variable new is printed as the output vector.

ALGORITHM

STEP 1: take the vector values into variable A

STEP 2: Consider new as the result vector

STEP 3: Calculate the vector sum using the + operator

STEP 4: First print the original vectors

STEP 5: Assign the result into vector new as new=(A+3)[(!is.na(A)) & A > 0]

STEP 6: Along with the above statement it checks A>0 and whether the element is missing or not using is.na(A)

STEP 7: print the vector new as result vector

 

R Source Code

                                          A = c(1, 2, NULL, 3, 4, NULL)
print("Original vector:")
print(A)
new = (A+3)[(!is.na(A)) & A > 0]
print("New vector:")
print(new)

                                      

OUTPUT

[1] "Original vector:"
[1] 5 6 7 8
[1] "New vector:"
[1] 8 9 10 11