As stated in the title.
I'm working myself through the Datacamp R tutorials and I find the instructions to be....lacking.
One of the more annoying oversights is that many of the basic functions are never defined or explained, among them the print() and paste()-functions. Some of the time I can use one and some of the time the other, right now this seems totally random to me.
I have scoured the internet in search of a clear-cut answer but come up short.
I will restate my question:
When can I use the print()-function and when do I have to insert a paste-function in the parentheis, print(paste())?
If you are at the R console then the result of any expression you type in is automatically printed so you don't need to specify print
so these are the same:
# same when typed into the R console
32
## [1] 32
print(32)
## [1] 32
however, automatic printing is not done in R scripts, in R functions or in any context where it is within the body of some larger expression such as within a for
or while
loop. Thus, to have 32
print from within a function use print
. In these cases nothing would have been printed had we not used print
.
f <- function() {
print(32)
}
x <- f()
## [1] 32
for(i in 1:3) print(32)
## [1] 32
## [1] 32
## [1] 32
Note that print
prints out a single object. If you want to print out several objects you can either use several print statements or else combine the objects into a single larger object. For example,
# print A and then print B
"A"
## [1] "A"
"B"
## [1] "B"
paste("A", "B", sep = ",") # create single char string and print it
## [1] "A,B"
c("A", "B") # create vector of two elements and print it out
## [1] "A" "B"
There is also cat
.
x <- "A"
y <- "B"
cat("x:", x, "y:", y, "\n")
## x: A y: B
paste
has nothing to do with printing. Its function is to take its arguments and create a character string out of them so paste("A", "B")
creates the character string "AB"
. Of course if you enter a paste
command at the R console since R prints out the value of any expression typed into it, the result of the paste will be printed out. Here are some examples of automatic printing assuming that these expressions are typed into the R console.
# assume these are typed into the R console
paste("A", "B") # R automatically prints result of paste
## [1] "A B"
paste(32) # 32 is converted to character; then R automatically prints it
## [1] "32"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.