简体   繁体   English

R- 在每一行数据帧之后插入另一个数据帧的行?

[英]R- Insert rows of another dataframe after every row of dataframe?

I have 2 dataframe: mydata1 and mydata2, both 222x80.我有 2 个数据框:mydata1 和 mydata2,都是 222x80。 I want to create a new dataframe in which after every row of mydata1 I add the row (same index) of mydata2.我想创建一个新的数据框,其中在 mydata1 的每一行之后添加 mydata2 的行(相同索引)。 I tried with transform function, but the output is duplicating the rows of the same dataframe.我尝试使用转换函数,但输出是复制同一数据帧的行。 I can't substitute all columns values.我不能替换所有列值。 If someone has suggestion, Thank you!!如果有人有建议,谢谢!!

insert.mydataFeat <- transform(mydata1, colnames(mydata1)=colnames(mydata2))
out.mydataFeat <- rbind(mydata1, insert.mydataFeat)
#reorder the rows
n <- nrow(mydata1)
out.mydataFeat<-out.mydataFeat[kronecker(1:n, c(0, n), "+"), ]
out.mydataFeat

You can use indexing trick after combining the data with rbind .将数据与rbind结合后,您可以使用索引技巧。

mydata1 <- data.frame(col1 = 1:5, col2 = 'A')
mydata2 <- data.frame(col1 = 6:10, col2 = 'B')

combine_df <- rbind(mydata1, mydata2)
combine_df <- combine_df[rbind(1:(nrow(combine_df)/2), 
                ((nrow(combine_df)/2) +1):nrow(combine_df)), ]

#   col1 col2
#1     1    A
#6     6    B
#2     2    A
#7     7    B
#3     3    A
#8     8    B
#4     4    A
#9     9    B
#5     5    A
#10   10    B

where在哪里

rbind(1:(nrow(combine_df)/2), ((nrow(combine_df)/2) +1):nrow(combine_df))

#     [,1] [,2] [,3] [,4] [,5]
#[1,]    1    2    3    4    5
#[2,]    6    7    8    9   10

the above creates a two row matrix with 1st row as row numbers from 1st dataframe and 2nd row as row numbers from second dataframe and we use that to subset combine_df .上面创建了一个两行矩阵,第一行作为第一个数据帧的行号,第二行作为第二个数据帧的行号,我们用它来子集combine_df

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM