根据其他数据集复制粘贴行

时间:2018-05-29 22:19:34

标签: r

我有一个数据集A和数据集B,想要在数据集A中复制并粘贴整行,并根据数据集B的ID信息在同一数据集中添加另一行。

数据集A:

dataA = data.frame(id = as.character(1:10),
    name = c("bob", "ryan", "sean", "brock", "kobe", "andy", "andrew", "stephanie", "emma", "monica"),
    place = c(rep("central",3), rep("western",3), rep("eastern",4)) )

数据集B:

id_2 = c('1', '3', '5')
data_2 = data.frame(id_2)

最终所需的数据集应如下所示:

dataA = data.frame(
  id = c('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '1', '3', '5'),
  name = c('bob','ryan','sean','brock','kobe','andy','andrew', 'stephanie',
         'emma','monica','bob','sean','kobe'),
  place = c(rep('central',3),rep('western',3),rep('eastern',4),
          'central','central','western') )

2 个答案:

答案 0 :(得分:2)

rbind(dataA,dataA[data_2$id_2,])

#    id      name   place
# 1   1       bob central
# 2   2      ryan central
# 3   3      sean central
# 4   4     brock western
# 5   5      kobe western
# 6   6      andy western
# 7   7    andrew eastern
# 8   8 stephanie eastern
# 9   9      emma eastern
# 10 10    monica eastern
# 11  1       bob central
# 12  2      ryan central
# 13  3      sean central

答案 1 :(得分:2)

将data_2合并到dataA以获取其他属性,然后绑定行:

library(dplyr)                                  # to use pipe operator

colnames(data_2) = 'id'                         # renaming col name for ease
data_2 %>% merge(dataA) %>% rbind(dataA)        # alt. use: dplyr's inner_join with bind_rows