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)
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 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.
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.
You asked two different questions:
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With