个性网
科学网R语言数据框合并函数merge()使用范例【转载+评述】

#########################

> df2 = data.frame(CustomerId=c(2,4,6),State=c(rep("Alabama",2),rep("Ohio",1)))
> df1
  CustomerId Product
1          1 Toaster
2          2 Toaster
3          3 Toaster
4          4   Radio
5          5   Radio
6          6   Radio
> df2
  CustomerId   State
1          2 Alabama
2          4 Alabama
3          6    Ohio
> merge(df1, df2, all=TRUE)
  CustomerId Product   State
1          1 Toaster    <NA>
2          2 Toaster Alabama
3          3 Toaster    <NA>
4          4   Radio Alabama
5          5   Radio    <NA>
6          6   Radio    Ohio
> merge(df1, df2, all.x=TRUE)
  CustomerId Product   State
1          1 Toaster    <NA>
2          2 Toaster Alabama
3          3 Toaster    <NA>
4          4   Radio Alabama
5          5   Radio    <NA>
6          6   Radio    Ohio
> merge(df1, df2, all.y=TRUE)
  CustomerId Product   State
1          2 Toaster Alabama
2          4   Radio Alabama
3          6   Radio    Ohio
#####################################

评述:

1、dataframe的填充默认按列填充

2、merge()函数较我们之前介绍的 cbind()和rbind()两个函数更加‘智能’

推荐