How it works...

In Step 1, we create a function that, given a vector, returns only a single value (a vector of length one). We then use it in mutate() to add a column called result and get the following:

## Sepal.Length Sepal.Width Petal.Length Petal.Width Species result 
## 1 5.1 3.5 1.4 0.2 setosa 563.7
## 2 4.9 3.0 1.4 0.2 setosa 563.7
## 3 4.7 3.2 1.3 0.2 setosa 563.7
## 4 4.6 3.1 1.5 0.2 setosa 563.7

Note how the single value the function returns in the result column is repeated over and over. With length == 1 vectors, R will recycle the result and place it in every position. 

In Step 2, we go to the opposite end and create a function that, given a vector, returns a vector of identical length (specifically, it returns a vector of the word result_ pasted onto a number representing the position in the vector). When we run it, we get this:

## Sepal.Length Sepal.Width Petal.Length Petal.Width Species result 
## 1 5.1 3.5 1.4 0.2 setosa result_1
## 2 4.9 3.0 1.4 0.2 setosa result_2
## 3 4.7 3.2 1.3 0.2 setosa result_3
## 4 4.6 3.1 1.5 0.2 setosa result_4

Because it is exactly the same length as the rest of the columns of the dataframe, R will accept it and apply it as a new column.

In Step 3, we create a function that returns a vector of three elements. As the length is neither one nor the length of the other columns of the dataframe, the code fails.

In Step 4, we look at how we can repeat an incompatible length vector to make it fit should we need to. The rep_until() function with the length.out argument repeats its input until the vector is length.out long. In this way, we get the following column, which is what we were hoping to see with the function in Step 3:

## Sepal.Length Sepal.Width Petal.Length Petal.Width Species result 
## 1 5.1 3.5 1.4 0.2 setosa A
## 2 4.9 3.0 1.4 0.2 setosa b
## 3 4.7 3.2 1.3 0.2 setosa C
## 4 4.6 3.1 1.5 0.2 setosa A
## 5 5.0 3.6 1.4 0.2 setosa b

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.72.70