【问题标题】:Add rep vector to dataframe with uneven total rows将代表向量添加到总行数不均匀的数据帧
【发布时间】:2019-05-23 21:31:24
【问题描述】:

我正在尝试找到一种方法来自动化大型数据集以添加两个因子,但数据可能包含不均匀的行。

我尝试使用“rep”函数来执行此操作,但这仅在数据框具有偶数时才有效。

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

如何让 data.frame 将 1 回收到第 5 行而不是报错?

【问题讨论】:

  • rep(1:2, length.out = 5)?
  • 感谢@sindri_baldur,但您的回答仅适用于单个数据帧,但在处理多个不同数据帧时不起作用,所有数据帧都具有不同的行长,即 1,133 行、1,865 行等。
  • rep(1:2, length.out = nrow(df)) 呢?
  • 谢谢@sindri_baldur,太棒了,我真的很感激

标签: r dataframe rep


【解决方案1】:

rep()length.out 参数是一种选择:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-06
    • 1970-01-01
    相关资源
    最近更新 更多