Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate numerical values in a string

I would like to store this output in a string:

> x=1:5 > cat("hi",x) hi 1 2 3 4 5 

So I use paste, but I obtain this different result:

> paste("hi",x) [1] "hi 1" "hi 2" "hi 3" "hi 4" "hi 5" 

Any idea how to obtain the string:

"hi 1 2 3 4 5" 

Thank you very much!

like image 316
kahlo Avatar asked Nov 07 '12 11:11

kahlo


People also ask

How can a numeric value be concatenated to a string?

The most obvious (and possibly the best) way to concatenate a string and a number is to use the CONCAT() function. This allows you to provide the string and the number as two separate arguments. SQL Server will then concatenate them, and your concatenation is complete.

Can string concatenation be done with numbers?

If you want to concatenate a string and a number, such as an integer int or a floating point float , convert the number to a string with str() and then use the + operator or += operator.

How do you concatenate a numeric variable to a string in Java?

String Concatenation using + Operator The easiest way of joining multiple String and numeric values in Java. Just remember that, when you have two or more primitive type values e.g. char, short, or int, at the beginning of your string concatenation, you need to explicitly convert the first of them to a String.

How do I concatenate a number and a string in SQL?

Another way to implement Concat in SQL with the numerical value is to use the CAST operator. This operator converts the numerical data into the string format. Using the + (plus) operator will manipulate the numeric data into string concatenation. You must convert the numerical data into a string data type.


2 Answers

You can force coercion to character for x by concatenating the string "hi" on to x. Then just use paste() with the collapse argument. As in

x <- 1:5 paste(c("hi", x), collapse = " ")  > paste(c("hi", x), collapse = " ") [1] "hi 1 2 3 4 5" 
like image 108
Gavin Simpson Avatar answered Oct 08 '22 18:10

Gavin Simpson


You could use capture.output with cat

capture.output(cat('hi',x)) [1] "hi 1 2 3 4 5" 
like image 43
mnel Avatar answered Oct 08 '22 20:10

mnel