0
votes

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?

1
Or rep(1:2, length.out = 5)? - sindri_baldur
Thanks @sindri_baldur but your answer is only sufficient for individual data frames, but will not work when dealing with multiple different data frames, all with different row lengths, i.e. 1,133 rows, 1,865 rows, etc. - Sparky
what about rep(1:2, length.out = nrow(df))? - sindri_baldur
Thanks @sindri_baldur, that's brilliant I really appreciate it - Sparky

1 Answers

1
votes

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

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