Search code examples
rdataframerep

Add rep vector to dataframe with uneven total rows


I'm trying to find a way of automating a large dataset to add two factors but the data may contain uneven rows.

I've tried to do this with the 'rep' function but this will only work if the data frame has even numbers.

x<-c(1,3,5,7,9)
y<-c(2,4,6,8,10)
df<-data.frame(x,y)
df$state<-factor(rep(1:2))   

Error in `$<-.data.frame`(`*tmp*`, state, value = 1:2) : 
replacement has 2 rows, data has 5

How do I get the data.frame to recycle 1 into row 5 instead of an error?


Solution

  • rep()'s length.out argument is one option:

    df$state<-factor(rep(1:2, length.out = nrow(df)))