两个数据框的交集

Intersection of two dataframes

我试图只保留两个数据帧共有的列和行。换句话说,我正在尝试过滤列名和一列的元素(包含日期):

到目前为止我试过了(来自这里的一个论坛):

common_cols <- intersect(colnames(df_tot), colnames(roe))
common_rows <-as.Date(intersect(df_tot$dates, roe$dates), origin = "1970-01-01")

df_tot[common_rows, common_cols]
roe[common_rows, common_cols]

但数据集只包含 NA。有人可以帮忙吗?

我尝试了一种不同的方法,现在有效了:

row.names(df_tot)<-df_tot$dates
row.names(roe)<-roe$dates

common_cols <- intersect(colnames(df_tot), colnames(roe))
common_rows <- intersect(rownames(df_tot), rownames(roe))

df_tot[common_rows, common_cols]
roe[common_rows, common_cols]

我编写了一些可重现的示例数据:

data(iris)

df_tot <- iris
roe    <- iris

colnames(roe) <- c("nonmatching.example", colnames(roe)[2:ncol(roe)])
roe$dates     <- seq(as.Date("1910/1/1"), by=1, length.out = nrow(roe))

df_tot$dates <- seq(as.Date("1910/3/1"), by=1, length.out = nrow(df_tot))


common_cols <- intersect(colnames(df_tot), colnames(roe))
common_rows <- as.Date(intersect(df_tot$dates, roe$dates))

df_tot[common_rows, common_cols]
roe[common_rows, common_cols]


table(is.na(df_tot[common_rows, common_cols]))
FALSE 
  750
tibble::glimpse(df_tot[common_rows, common_cols]) # use head() or summary() if you don't have the library tibble
Observations: 150
Variables: 5
$ Sepal.Width  <dbl> 3.5, 3.0, 3.2, 3.1, 3.6, 3.9, 3.4, 3.4, 2.9, 3.1, 3.7, 3.4, 3.0, 3.0, 4.0, 4.4, 3.9, 3.5, 3.8, 3.8, 3.4, 3.7, 3.6, 3.3, 3.4, 3.0, 3.4, 3.5,...
$ Petal.Length <dbl> 1.4, 1.4, 1.3, 1.5, 1.4, 1.7, 1.4, 1.5, 1.4, 1.5, 1.5, 1.6, 1.4, 1.1, 1.2, 1.5, 1.3, 1.4, 1.7, 1.5, 1.7, 1.5, 1.0, 1.7, 1.9, 1.6, 1.6, 1.5,...
$ Petal.Width  <dbl> 0.2, 0.2, 0.2, 0.2, 0.2, 0.4, 0.3, 0.2, 0.2, 0.1, 0.2, 0.2, 0.1, 0.1, 0.2, 0.4, 0.4, 0.3, 0.3, 0.3, 0.2, 0.4, 0.2, 0.5, 0.2, 0.2, 0.4, 0.2,...
$ Species      <fctr> setosa, setosa, setosa, setosa, setosa, setosa, setosa, setosa, setosa, setosa, setosa, setosa, setosa, setosa, setosa, setosa, setosa, se...
$ dates        <date> 1910-03-01, 1910-03-02, 1910-03-03, 1910-03-04, 1910-03-05, 1910-03-06, 1910-03-07, 1910-03-08, 1910-03-09, 1910-03-10, 1910-03-11, 1910-0...