Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does dplyr::mutate() not recycle vectors?

Tags:

r

dplyr

It seems as if creating a column with dplyr::mutate() does not allow vector recycling. Why?

Example:

require(dplyr)
df <- data_frame(id = rep(1:5, each = 42), name = rep(letters[1:7], each = 6, times = 5))

now:

df %>% mutate (tp = c(1:42))  #results in 

Error in mutate_impl(.data, dots) : 
  Column `tp` must be length 210 (the number of rows) or one, not 42

but of course

df$tp <- c(1:42) #works

Is my mutate code wrong or does recycling simply not work in mutate()? If it helps, I am using dplyr 0.7.2 with RStudio 1.0.153 (Mac)

like image 454
tjebo Avatar asked Jan 15 '18 23:01

tjebo


People also ask

What does mutate do in dplyr?

mutate() adds new variables and preserves existing ones; transmute() adds new variables and drops existing ones. New variables overwrite existing variables of the same name.

What is the use of mutate function in r?

What is the mutate() function in R? We can use the mutate() function in R programming to add new variables in the specified data frame. These new variables are added by performing the operations on present variables. Before using the mutate() function, you need to install the dplyr library.

What is Vector recycling in R?

R Vector Recycling is a process in which two vectors are involved in an operation, that operation needs the vectors to be of same length, and R repeats the elements of shorter vector to match the length of longer vector.


1 Answers

You asked two different questions:

  • (title) "Does dplyr::mutate() not recycle vectors?"

A: no (as you found out). The dplyr vignette makes it clear that recycling only works for length-1 vectors:

They [vector values used in mutate()] must be either length 1 (they then get recycled) or have the same length as the number of rows.

  • Why?

A: Probably impossible to answer without asking the dplyr developers. I would speculate that they reached a different conclusion about the tradeoff between convenience (on the one hand) and requiring explicit statements of user intentions (on the other hand) from the original developers of R (who even allowed incomplete recycling, albeit with a warning).

like image 102
Ben Bolker Avatar answered Oct 17 '22 03:10

Ben Bolker