What are the differences between concatenating strings with cat() and paste()?

前端 未结 1 341
一整个雨季
一整个雨季 2020-12-03 07:06

What are the differences between concatenating strings with cat and paste?

In particular, I have the following questions.

相关标签:
1条回答
  • 2020-12-03 07:21

    cat and paste are to be used in very different situations.


    paste is not print

    When you paste something and don't assign it to anything, it becomes a character variable that is print-ed using print.default, the default method for character, hence the quotes, etc. You can look at the help for print.default for understanding how to modify what the output looks like.

    • print.default will not evaluate escape characters such as \n within a character string.

    Look at the answers to this question for how to capture the output from cat.


    Quoting from the easy to read help for cat (?cat)

    Concatenate and Print

    Description

    Outputs the objects, concatenating the representations. cat performs much less conversion than print.

    ...

    Details

    cat is useful for producing output in user-defined functions. It converts its arguments to character vectors, concatenates them to a single character vector, appends the given sep= string(s) to each element and then outputs them.

    Value

    None (invisible NULL).

    cat will not return anything, it will just output to the console or another connection.

    Thus, if you try to run length(cat('x')) or mode(cat('x')), you are running mode(NULL) or length(NULL), which will return NULL.


    The help for paste is equally helpful and descriptive

    Concatenate Strings

    Description

    Concatenate vectors after converting to character.

    ....

    Value

    A character vector of the concatenated values. This will be of length zero if all the objects are, unless collapse is non-NULL in which case it is a single empty string.

    0 讨论(0)
提交回复
热议问题