What is the difference between cat and print?

前端 未结 2 510
迷失自我
迷失自我 2020-12-04 14:20

cat and print both seem to offer a \"print\" functionality in R.

x <- \'Hello world!\\n\'
cat(x)
# Hello world!
print(x)
# [1] \         


        
2条回答
  •  孤城傲影
    2020-12-04 15:08

    An essential difference between cat and print is the class of the object they return. This difference has practical consequences for what you can do with the returned object.

    print returns a character vector:

    > print(paste("a", 100* 1:3))
    [1] "a 100" "a 200" "a 300"
    
    > class(print(paste("a", 100* 1:3)))
    [1] "a 100" "a 200" "a 300"
    [1] "character" 
    

    cat returns an object of class NULL.

    > cat(paste("a", 100* 1:3))
    a 100 a 200 a 300
    
    > class(cat(paste("a", 100* 1:3)))
    a 100 a 200 a 300[1] "NULL"
    

    In some cases, it is important to return the output as is in your console, for example when you want to copy-paste the output. In those cases, you really don't want to return a character vector. I found it a useful strategy in those cases to combine print and cat: Use print to create the object, use cat to print it to your console.

    > output <- print(paste("a", 100* 1:3)) # use print to create the object
    > cat(output) # use cat to print it *as is* to your console
    a 100 a 200 a 300
    

    Using xtable package for printing LaTeX tables in R:

    > require(xtable)
    > df <- data.frame(a = 1, č = 5) # dataframe with foreign characters
    > output <- print(xtable(df), include.rownames = FALSE)
    > output <- gsub("č", "c", output) # replace foreign characters before 
    > # copying to LaTeX
    
    > cat(output)
    \begin{table}[ht]
    \centering
    \begin{tabular}{rr}
    \hline
    a & c \\
    \hline
    1.00 & 5.00 \\ 
    \hline
    \end{tabular}\end{table}
    
    > print(output)
    [1] "\\begin{table}[ht]\n\\centering\n\\begin{tabular}{rr}\n  
    \hline\na & c    \\\\ \n  \\hline\n1.00 & 5.00 \\\\ \n   
    \\hline\n\\end{tabular}\n\\end{table}\n"
    

提交回复
热议问题