w3resource

R Programming: Concatenate a vector

R Programming: Vector Exercise-21 with Solution

Write a R program to concatenate a vector.

Sample Solution :

R Programming Code :

# Create a vector 'a' with three string elements: "Python", "NumPy", "Pandas"
a = c("Python", "NumPy", "Pandas")

# Print the original vector 'a'
print(a)

# Concatenate the elements of vector 'a' into a single string without spaces
x = paste(a, collapse = "")

# Print a message indicating the result of the concatenation
print("Concatenation of the said string:")

# Print the concatenated string 'x'
print(x)

Output:

[1] "Python" "NumPy"  "Pandas"
[1] "Concatenation of the said string:"
[1] "PythonNumPyPandas"                         

Explanation:

  • Create a vector:
    • a = c("Python", "NumPy", "Pandas")
      A vector a is created containing three string elements: "Python", "NumPy", and "Pandas".
  • Print the original vector:
    • print(a)
      Displays the elements of the vector a in their original order.
  • Concatenate the elements of the vector:
    • x = paste(a, collapse = "")
      Uses the paste() function to concatenate all elements of vector a into a single string without any separators (specified by collapse = "").
  • Print message (Concatenation result):
    • print("Concatenation of the said string:")
      Prints the message "Concatenation of the said string:" to indicate the next output will show the concatenated result.
  • Print the concatenated string:
    • print(x)
      Displays the concatenated string x, which combines "Python", "NumPy", and "Pandas" into one continuous string: "PythonNumPyPandas".

R Programming Code Editor:



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

Previous: Write a R program to reverse the order of given vector.
Next: Write a R program to count number of values in a range in a given vector.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/r-programming-exercises/vector/r-programming-vector-exercise-21.php