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

February 8, 2023, Learn eTutorial
1455

How to add 3 to each element in a given vector in R programming?

Here we explain how to write an R program to add 3 to each element in a given vector. For that, we had one vector value to add three to each one of its components. 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 not, it will return the boolean value TRUE. The syntax of is.na() function is

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

In this R program, we accept the vector values into variables A. The result after adding 3 to each element is stored in a variable new. we are adding 3 to each vector value using the + operator and the function using the formula new=(A+3)[(!is.na(A)) & A > 0], Finally the value inside the 'new' variable 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 the result vector

R Source Code

```                                          ```A = c(5, 6, NULL, 7, 8, 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
```

VIEW ALL
VIEW ALL