1. paste is a very useful function in creating strings with certain patterns. In
ID: 3586367 • Letter: 1
Question
1. paste is a very useful function in creating strings with certain patterns. In the following example, it can automatically concatenate numerical and character values together. In other programing languages, they usually can't be as smart because these two data types are not compatible, unless conversions are explicilty done. Please explain what happens in terms of data coercing and object recycling. paste (c ( " first-name", ' last, name ' ) , "-", 1 : 6, sep = [1] [5] "first_name_1" "first-name-5 " "Last_name_2" "last-name-6" "first-name-3" "Last-name-4 "Explanation / Answer
Let us understand data coering in the following way:
Let us create a vector with some three numbers or any numeric data and print the vector:
a <- c(1,2,3)
sum(a)
a
Output:
[1] 6
[1] 1 2 3
We created a vector with three values 1,2 and 3 and using the built-in sum function to find sum.
Now consider the following code:
a <- c(a, “hi”)
a
Output:
[1] “1” “2” “3” “hi”
So here the content of the vecor which were numbers are converted into string type. Thus automatically the numeric data type was converted into string type. This is implicit type conversion also called data coercion.
The general rule of data coering for a programming language is that “the bigger type wins.” Strings can represent more data than numeric values, so the numeric values are automatically converted to strings. Opposite is not true.
Now let us understand object Recycling in the following way:
Consider two vectors and an associated operation.
applying any operation to 2 vectors requires the two vectors to be of same length . The object Recycling features automatically recycles/repeats the shorter vector till it's long enough to match the longer vector.
Consider the following example:
> c(9,21,42) + c(5,1,10,24,31)
Output:
[1] 14 22 52 33 52
Warning message:
In c(9, 21, 42) + c(5, 1, 10, 24, 31) :
longer object length is not a multiple of shorter object length
So in this case the shorter vector was recycled/ repeated and for this operation it was taken like : c(9, 21, 42, 9, 21)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.