Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print text and variables in a single line in r

Tags:

r

Is there a way to print text and variables in a single line in r

eg

a="Hello"
b="EKA"
c="123456"

print("$a !! my name is $b and my number is $c")

out put will be like this

Hello !! my name is EKA and my number is 123456
like image 741
Eka Avatar asked Aug 27 '15 06:08

Eka


People also ask

How do I print two things on the same line in R?

You can use the cat() function to easily print multiple variables on the same line in R. This function uses the following basic syntax: cat(variable1, variable2, variable3, ...)

How do you print a string and a variable together in R?

R provides a method paste() to print output with string and variable together. This method defined inside the print() function. paste() converts its arguments to character strings. One can also use paste0() method.

How do I print text and numbers in R?

To display ( or print) a text with R, use either the R-command cat() or print(). Note that in each case, the text is considered by R as a script, so it should be in quotes.


3 Answers

I'd suggest using sprintf function. The advantage of this function is, that the variables can be of any class (here, c is numeric).

a="Hello"
b="EKA"
c=123456

sprintf("%s !! my name is %s and my number is %i", a, b, c)
like image 73
MarkusN Avatar answered Nov 03 '22 19:11

MarkusN


print( paste("You have choosen the following file name: ", fileName)) 

will do the job

like image 44
Elligno Avatar answered Nov 03 '22 19:11

Elligno


I like to do this: print(c('x=',x)) The output format is messy but all and all it is most convenient and flexible method I know (it works INSIDE FUNCTIONS unlike the sprintf solution & it can handle more data types too).

It is much faster to type than: print(paste('x=',x)). Which is rather cumbersome for a simple print function!

Notable Alternative: cat('x=',x,'\n')

I tend to avoid this also because I find it tedius to always specify the newline character. Although technically it was 'the function' that was invented to easily do what you are asking, it was designed poorly IMO.

like image 27
profPlum Avatar answered Nov 03 '22 18:11

profPlum