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
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, ...)
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.
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.
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)
print( paste("You have choosen the following file name: ", fileName))
will do the job
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With