+1 vote
in R Programming by (3.4k points)
edited by

How can I merge and combine two values in R? For instance:

tmp = cbind("QWE", "RT")
#      [,1]  [,2]
# [1,] "QWE" "RT"

Now I want to concentrate these both tmp values from the syntax above to single str:

tmp_new = "QWE,RT"

How can I perform this?

1 Answer

0 votes
by (26.9k points)

It is a basic function and rather an useful one, to concentrate strings in r use paste() function, see this syntax for instance:

 paste(…, sep="", collapse=NULL)

 here in this syntax paste is the keyword, ... is the input strings which we have to separate using commas, sep is a character that appends between two adjacent strings and behaves as a separator and last one is collapse which is an optional character used to separate the results.

 Paste is used to convert the arguments to character strings and separates them by the string given by sep. In case of vector arguments, they are concatenated term-by-term to give a character vector result.

Check these examples:

  • To concatenate two strings:


str1 = 'QWE'

str2 = 'RT!'

# concatenate two strings using paste function

result = paste(str1,str2)

print (result)


 $ Rscript r_strings_concatenate_two.R 

[1] "QWE RT!"

  •  for more than one string

str1 = 'QWE'

str2 = 'RT!'

str3 = 'Y'

str4 = 'Keyboard!'

# concatenate two strings using paste function

result = paste(str1,str2,str3,str4,sep="-")

print (result)


 $ Rscript r_strings_concatenate_multiple.R 

[1] "QWE-RT-Y-Keyboard!"

Happy Learning.....!!