Search code examples
rrep

Error in R: I should use rep() but I already do


I'm using a small code in R:

dat$colour<-rep(rainbow(4)) #you get a warning if you not have a multiple of 4 records, but that is ok.

dat consists of seven rows. I've included rep() to make sure that the colours can be repeated even though seven is not a multiple of four. However, I still get the following error:

Error in set(x, j = name, value = value) : Supplied 4 items to be assigned to 7 items of column 'colour'. If you wish to 'recycle' the RHS please use rep() to make this intent clear to readers of your code.

To reproduce:

dat <- data.table('Year' = c(2010, 2011, 2012, 2013, 2014, 2015, 2016))
dat$colour<-rep(rainbow(4))

I would really value the help, the script is automated but now gives me this error. I have just switched to a new computer, the problem may lie in an incorrect version of this or that.

Thanks!


Solution

  • You can use rep_len:

    dat$colour <- rep_len(rainbow(4), nrow(dat))