Strings
We need formatting and display of strings to obtain the results of specific operations in required format.- Formatting and Display of Strings
- Operations with Strings
Formatting and Display of Strings
Important commands regarding formatting and display are
print , format , cat and paste
print function prints its argument.
Usage
print ( )
print ( ) is a generic command that is available for every object class.
Examples:
> print (sqrt(2) )
[1] 1.414214
> print ( sqrt (2) , digits = 5)
[1] 1.4142
Format an R object for pretty printing.
Usage
format (x, ...)
x is any R object; typically numeric.
format (x, trim = FALSE, digits = NULL, nsmall = OL, justify = c("left" , "right" , "center" , "none") , width = NULL, . . .)
digits→shows how many significant digits are to be used.
nsmal→shows the minimum number of digits to the right of the decimal point.
justify→provides left-justified (the default), right-justified, or centered.
Examples:
> print (format ( 0.5, digits = 10, nsmall = 15) )
[1] "0.500000000000000"
Matrix display
> x <- matrix (nrow = 3, ncol = 2, data = 1:6, byrow = T)
> print (x)
[,1] [,2]
[1,] 1 2
[2,] 3 4
[3,] 5 6
Here, a matrix is displayed in the R command window.
One can specify the desired number of digits with the option digits.
The print function has a significant limitation that it prints only one object at a time.
Trying to print multiple items gives error message:
> print ("The zero occurs at", 2*pi, "radians.") Error in print.default("The zero occurs at",2*pi, "radians.") :
invalid 'quote' argument
The only way to print multiple items is to print them one at a time
> print ("The zero occurs at"); print (2*pi) ; print ("radians")
[1] "The zero occurs at"
[1] 6.283185
[1] "radians"
The cat function is an alternative to print that lets you combine multiple items into a continuous output.
0 Comments:
Post a Comment