合并两个数据框,重复一个的值以填充R中的另一个

rbl8hiat  于 2023-03-27  发布在  其他
关注(0)|答案(1)|浏览(144)

我在r中有两个dataframe,如下所示:

df1 <- data.frame(tracks = rep(c(0:4), each=16), nodes = rep(c("nose", "eyeR", "eyeL", "head", "spine1", "spine2", "caudal", "tail"), length.out=80), coordinates = rep(c("x", "y"), length.out=80))
df2 <- as.data.frame(matrix(runif(n=4000, min=0, max=700), nrow=50))

基本上df 1包含df 2的标签信息。我需要一个输出df,其中我基本上有df 1的第4列,这是df 2的每一列堆叠在彼此的顶部,并且df 1的相应行标签重复,但是df 2有很多行(在这种情况下是50,但在我自己的数据集中要大得多)。任何帮助都将不胜感激!谢谢。

cmssoen2

cmssoen21#

您可以使用rep()函数创建df1的行的副本,然后使用cbind()将两者粘在一起。

df1 <- data.frame(tracks = rep(c(0:4), each=16), nodes = rep(c("nose", "eyeR", "eyeL", "head", "spine1", "spine2", "caudal", "tail"), length.out=80), coordinates = rep(c("x", "y"), length.out=80))
df2 <- as.data.frame(matrix(runif(n=4000, min=0, max=700), nrow=50))
rep_df1 <- as.data.frame(lapply(df1, rep, each = nrow(df2)))
cbind(rep_df1, df2)

这给出了一个输出,其中前几行和列如下所示:

tracks nodes coordinates         V1        V2       V3        V4
1       0  nose           x  18.791475  89.43616 371.6074 272.61443
2       0  nose           x  50.063596 436.08428 209.1694  97.48476
3       0  nose           x 146.009226 582.71412 373.5483 470.81447
4       0  nose           x 435.155961 205.98816 628.5954 540.18555
5       0  nose           x  24.587971 480.34638 405.0276 158.46942
6       0  nose           x 246.314712 468.34386 227.4254 388.98637
7       0  nose           x 306.463035 269.85774 576.8909 507.84488
8       0  nose           x 544.223864 300.51239 474.8472  72.82660

如果需要,您可以使用pivot_longer()进一步重塑数据。

相关问题