Search code examples
rdplyrrep

rep invalid 'times' argument in dplyr summarize


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)


Solution

  • 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