按行索引和列标签合并

时间:2018-05-23 19:45:44

标签: r dataframe indexing merge

> df1
   x  y
1 13  7
2 14  8
4 16 10
5 17 11
6 18 12


> df2
  index_df1 y
1         2 a
2         4 d
3         5 e
4         6 f

如何将df1df2合并,索引为df1"index_df1"列为df2。像:

z <- merge(df1, df2, by.x = 0, by.y = "index_df1", all.x = TRUE)

1 个答案:

答案 0 :(得分:0)

您可以使用dplyr::left_join将两个data.frames合并为:

library(dplyr)

df1 %>% mutate(rn = row_number()) %>%
  left_join(df2, by = c("rn" = "index_df1")) %>%
  select(-rn)

#    x y.x  y.y
# 1 13   7 <NA>
# 2 14   8    a
# 3 15   9 <NA>
# 4 16  10    d
# 5 17  11    e
# 6 18  12    f

已更新:根据OP的反馈。如果行在df1中不是连续的,那么选项可以是:

# Use `index_df1` to add a column having value of x in df1
df2$x <- df1[df2$index_df1,"x"]

# Now, merge
merge(df1, df2[,c("y", "x")], by.x = "x", by.y = "x", all.x = TRUE)
#    x y.x  y.y
# 1 13   7 <NA>
# 2 14   8    a
# 3 15   9 <NA>
# 4 16  10    d
# 5 17  11    e
# 6 18  12    f