问题
What are the differences between concatenating strings with cat and paste?
In particular, I have the following questions.
Why does R not use the double quote (
") when it prints the results of callingcat(but it uses quotes when usingpaste)?> cat("test") test > paste("test") [1] "test"Why do the functions
lengthandmode, which are functions available for almost all objects in R, not "work" oncat?> length(cat("test")) test[1] 0 > mode(cat("test")) test[1] "NULL"Why do C-style escape sequences work with
cat, but not withpaste?> cat("1)Line1\n 2)Line2\n 3)Line3") 1)Line1 2)Line2 3)Line3 > paste("1)Line1\n 2)Line2\n 3)Line3") [1] "1)Line1\n 2)Line2\n 3)Line3"Why doesn't R's recycling rule work with
cat?> cat("Grade", c(2, 3, 4, 5)) Grade 2 3 4 5 > paste("Grade", c(2, 3, 4, 5)) [1] "Grade 2" "Grade 3" "Grade 4" "Grade 5"
回答1:
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.defaultwill not evaluate escape characters such as\nwithin 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.
catperforms much less conversion than...
Details
catis useful for producing output in user-defined functions. It converts its arguments tocharactervectors, concatenates them to a singlecharactervector, appends the givensep= 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
charactervector of the concatenated values. This will be of length zero if all the objects are, unless collapse is non-NULLin which case it is a single empty string.
来源:https://stackoverflow.com/questions/12775085/what-are-the-differences-between-concatenating-strings-with-cat-and-paste