rep invalid 'times' argument in dplyr summarize

uRals picture uRals · Oct 17, 2016 · Viewed 7.8k times · Source

I have some problem with rep function in dplyr, for example code like this works fine

d <- data.frame(x=1:10,y=1:2) %>% 
  group_by(y) %>%
  summarize(rep.sum =sum(rep(x,y)))

but if I run something like this

d <- data.frame(x=1:10,y=1:2) %>% 
  group_by(y) %>%
  summarize(rep.sum =sum(rep(1,y)))

I am getting error

Error: invalid 'times' argument

What am I doing wrong?

(dplyr version 0.5.0)

Answer

Data Munger picture Data Munger · Oct 17, 2016

Take a close look at the help page for 'rep'. The 'times' vector has to be the same length as the first argument, or of length 1:

> rep(1, 2)
[1] 1 1
> rep(1, c(2,2))
Error in rep(1, c(2, 2)) : invalid 'times' argument
> rep(1:3,2)
[1] 1 2 3 1 2 3