dplyr :: mutate()是否不回收向量? [英] Does dplyr::mutate() not recycle vectors?
问题描述
似乎使用 dplyr :: mutate()
创建列不允许向量回收.为什么?
It seems as if creating a column with dplyr::mutate()
does not allow vector recycling. Why?
示例:
require(dplyr)
df <- data_frame(id = rep(1:5, each = 42), name = rep(letters[1:7], each = 6, times = 5))
现在:
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
当然可以
df$tp <- c(1:42) #works
我的mutate代码是否错误,或者回收在 mutate()
中根本不起作用?如果有帮助,我正在将 dplyr
0.7.2与RStudio 1.0.153(Mac)
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)
推荐答案
您问了两个不同的问题:
You asked two different questions:
- (标题)"dplyr :: mutate()不回收载体吗?"
A:否(如您所知). dplyr小插图清楚地表明,回收仅适用于长度为1的向量:
A: no (as you found out). The dplyr vignette makes it clear that recycling only works for length-1 vectors:
它们[在
mutate()
中使用的矢量值"必须为长度1(然后将其回收)或具有与行数相同的长度.
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:如果不问 dplyr
开发人员,可能无法回答.我推测他们在便利性(一方面)与要求R的原始开发人员(甚至允许 incomplete >回收,尽管有警告).
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).
这篇关于dplyr :: mutate()是否不回收向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!