w3resource

R Programming: Add 3 to each element in a given vector. Print the original and new vector

R Programming: Vector Exercise-27 with Solution

Write a R program to add 3 to each element in a given vector. Print the original and new vector.

Sample Solution :

R Programming Code :

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

Sample Output:

[1] "Original vector:"
[1] 1 2 3 4
[1] "New vector:"
[1] 4 5 6 7                         

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a R program to test whether the value of the element of a given vector greater than 10 or not. Return TRUE or FALSE.
Next: Write a R program to create a vector using : operator and seq() function.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.