R Program to concatenate a vector

How to concatenate a vector

Here we are explaining how to write an R program to concatenate a vector. Here we are using a built-in function paste(), collapse() for this . Function paste() helps to concatenate vectors after converting to characters.The collapse() function helps to collapses a character vector of any length into a length 1 vector. The syntax of this method is like

paste0(…, collapse = NULL)

– where …(dots) indicates one or more R objects, to be converted to character vectors and collapse is an optional character string to separate the results

collapse(x, sep = ““, width = Inf, last =”“)

– where x is the character vector to collapse, sep is the character string to separate the term. The maximum string width before truncating is indicated by width finally, the last is the last string used to separate the last two items.

How to concatenate a vector in the R program

Below are the steps used in the R program to concatenate a vector. In this R program, we directly give the values to built-in functions. And print the function result. Here we used variable A for assigning vector values. And variable B for holding the concatenated string. The string is concatenated by calling like B = paste(A, collapse = ““). Finally print the concatenated string.

ALGORITHM

  • STEP 1: Assign variable A with vector values
  • STEP 2: First print original vector values
  • STEP 3: Concatenate the vector A and save to variable B as B = paste(A, collapse = ““)
  • STEP 4: print the result vector B

R Source Code

A = c("Java", "Python", "Php")
print(A)
## [1] "Java"   "Python" "Php"
B = paste(A, collapse = "")

print("Concatenation of the string:")
## [1] "Concatenation of the string:"
print(B)
## [1] "JavaPythonPhp"