Add rep vector to dataframe with uneven total rows

空扰寡人 提交于 2021-02-17 06:05:24

问题


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:


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

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


来源:https://stackoverflow.com/questions/56275980/add-rep-vector-to-dataframe-with-uneven-total-rows

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!