首页 > 解决方案 > 如何通过重复 1 列并按顺序重复原始数据框的第 2 列来创建新的数据框?

问题描述

我试图通过重复 original-df 第 1 列中的值并将它们对应于 original-df 第 2 列中的重复值来创建新的数据框。但是,每列的值应该以不同的方式重复。例如,来自 original-df 第 1 列的值将重复为 1,2,3,1,2,3,1,2,3。其中原始df第2列的值应重复为1,1,1,2,2,2,3,3,3。

#here is original df
df1<-data.frame(x=1:3, y=10:12)

#I've tried the followig:
data.frame(x=df1$x,y=df1[,2])->df2

range<-1:3
data.frame(x=df1$x,y=df1$y[range,2])->df3

#I then tried this:
rep(df1$x,df1$y[l,2])->df4


#output either looks like this:
   x  y
1  1 10
2  2 11
3  3 12

#Or I receive an error message:
Error in df1$y[1, 2] : incorrect number of dimensions


#I expect data output to look like this:
  x  y
  1  10
  2  10
  3  10
  1  11
  2  11
  3  11
  1  12
  2  12
  3  12

标签: rdataframerepeatsequential

解决方案


一个选择是expand

library(tidyr)
expand(df1, x, y)

expand.gridbase R

do.call(expand.grid, df1)

推荐阅读