w3resource

R Programming: Add 3 to each element in a Vector and Print results


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 :

# Create a vector 'v' with elements 1, 2, NULL, 3, 4, NULL
v = c(1, 2, NULL, 3, 4, NULL)

# Print a message indicating the original vector
print("Original vector:")

# Print the content of the vector 'v'
print(v)

# Add 3 to each element of 'v', exclude NA values, and filter out non-positive values
new_v = (v + 3)[(!is.na(v)) & v > 0]

# Print a message indicating the new vector
print("New vector:")

# Print the content of the new vector after addition
print(new_v)

Output:

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

Explanation:

  • Create a vector:
    • v = c(1, 2, NULL, 3, 4, NULL)
      A vector v is created containing the elements 1, 2, NULL, 3, 4, and NULL.
  • Print message (Original vector):
    • print("Original vector:")
      Prints a message indicating that the following output will display the original vector.
  • Display the original vector:
    • print(v)
      Displays the content of the vector v. Note that NULL values are not included in the printed output.
  • Add 3 to each element and filter:
    • new_v = (v + 3)[(!is.na(v)) & v > 0]
      Adds 3 to each element in v. Elements that are NA or non-positive (including NULL, which is treated as NA in this context) are filtered out. The result is stored in new_v.
  • Print message (New vector):
    • print("New vector:")
      Prints a message indicating that the following output will display the new vector.
  • Display the new vector:
    • print(new_v)
      Displays the content of the new vector new_v, which contains elements from v increased by 3 and filtered according to the condition.

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.