Cleaning environment and console
rm(list=ls())
Lets first see how the cat() function works :
cat("Football", "is", "better","than","cricket")
## Football is better than cricket
The cat() function joins the three strings together into a single string as we can observe above.
BUT can we store it in a variable ? Lets try that :
result_cat = cat("Football", "is", "better","than","cricket")
## Football is better than cricket
We get NULL value as you can observe in the console below :
result_cat
## NULL
This is due to the cat() function’s lack of result storage.
Now lets try the paste() function instead, and see how its different :
paste("Football", "is", "better","than","cricket")
## [1] "Football is better than cricket"
Notice how paste() function printed to console in “” instead of cat() function. Since paste() function gives character output, it can be saved into a vector. lets see that:
result_paste = paste("Football", "is", "better","than","cricket")
Because the paste() function saves the output in a character variable, we can inspect the concatenated string.
Now there are benefits of this. Since paste() helps us save a concatenated string as character, we can use character functions like nchar() to inspect the string
nchar(result_paste)
## [1] 31
BONUS
There is a function also called paste0 which will likely be used more by you when you start using R regularly.
But how is it different than paste() we already used?
Let’s see it in action:
result_paste0 = paste0("Football", "is", "better","than","cricket")
Just like the name indicates “0” means no spaces, you can alternatively use the ‘collapse =’ command to include spaces which gives the user more control while concatenation.
result_paste0_collapsed = paste0(c("Football", "is", "better","than","cricket"), collapse = "-")
Only caveat is you have to add the strings in combine i.e. c() function internally, which you will get used to once you see the applicability of paste0 in many webscraping codes for R.
Thanks for watching the video, see you in the next one :)