简体   繁体   English

R 查找多个数据帧的匹配列名

[英]R Finding matched column names of multiple data frames

I have a dataset with various dataframes named "data_t1", "data_t2", ...., "data_t10".我有一个数据集,其中包含名为“data_t1”、“data_t2”、....、“data_t10”的各种数据框。

Some of those dataframes share the same variables.其中一些数据框共享相同的变量。 Therefore I am trying to find out which variables are shared by each two df.因此,我试图找出每两个 df 共享哪些变量。

Instead of comparing the column names of each df with the column names of all the other dataframes manually, i tried to find matching column names by coding a for loop.我没有手动将每个 df 的列名与所有其他数据帧的列名进行比较,而是尝试通过编写 for 循环来查找匹配的列名。 This is my code so far:到目前为止,这是我的代码:

 for (i in 1:10){
      for (j in 1:10){
        assign(paste("common_column_names",toString(i),toString(j),sep="_"), 
           intersect(colnames(noquote(paste("data_t",toString(i),sep=""))), 
                     colnames(noquote(paste("data_t",toString(j),sep="")))))
        }}

Although i know the df share variables, the output keeps being "NULL".虽然我知道 df 共享变量,但 output 一直是“NULL”。 The problem seems to be within the colnames() command, because问题似乎在 colnames() 命令中,因为

colnames(noquote(paste("data_t1")))

generates the Output NULL, whereas生成 Output NULL,而

colnames(data_t1)

generates a list of the colnames of "data_t1".生成“data_t1”的列名列表。

I was unable to find a solution for this problem so far.到目前为止,我无法找到解决此问题的方法。

Thanks.谢谢。

Here is a one-liner with Reduce .这是一个带有Reduce的单行代码。 Change the dataframes list name from df_list to your list name and it should work.将数据框列表名称从df_list更改为您的列表名称,它应该可以工作。

Reduce(function(x, y){intersect(x, names(y))}, df_list, init = names(df_list[[1]]))
#[1] "X"

Test data creation code测试数据创建代码

The code below makes sure there is a common column name, "X" and at least one different name in every dataframe, LETTERS[i] .下面的代码确保在每个 dataframe, LETTERS[i]中有一个通用的列名"X"和至少一个不同的名称。

set.seed(2021)
df_list <- lapply(1:4, function(i){
  df <- data.frame(1:5, 6:10, 11:15)
  names(df) <- c("X", LETTERS[i], sample(LETTERS, 1))
  df
})
names(df_list) <- paste0("data_t", 1:4)

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

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