有没有一种简单的方法来判断存储在一个列表中的许多数据帧是否包含相同的列? [英] Is there an easy way to tell if many data frames stored in one list contain the same columns?

查看:56
本文介绍了有没有一种简单的方法来判断存储在一个列表中的许多数据帧是否包含相同的列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含许多数据帧的列表:

I have a list containing many data frames:

df1 <- data.frame(A = 1:5, B = 2:6, C = LETTERS[1:5])
df2 <- data.frame(A = 1:5, B = 2:6, C = LETTERS[1:5])
df3 <- data.frame(A = 1:5, C = LETTERS[1:5])
my_list <- list(df1, df2, df3)

我想知道此列表中的每个数据框是否包含相同的列(即,相同数量的列,它们的名称和顺序相同).

I want to know if every data frame in this list contains the same columns (i.e., the same number of columns, all having the same names and in the same order).

我知道您可以使用lapply轻松找到列表中数据框的列名:

I know that you can easily find column names of data frames in a list using lapply:

lapply(my_list, colnames)

有没有一种方法可以确定列名称是否发生任何差异?我意识到这是一个涉及成对比较的复杂问题.

Is there a way to determine if any differences in column names occur? I realize this is a complicated question involving pairwise comparisons.

推荐答案

这是使用Reduce的另一个base解决方案:

Here's another base solution with Reduce:

!is.logical(
  Reduce(function(x,y) if(identical(x,y)) x else FALSE
         , lapply(my_list, names)
         )
)

您还可以使用

!is.logical(
  Reduce(function(x,y) if(identical(x,y)) x else FALSE
         , lapply(my_list, function(z) sort(names(z)))
         )
)

关于正在发生的事情,Reduce()在列表中累积.首先,评估identical(names_df1, names_df2).如果是真的,我们希望它返回相同的向量!然后,我们可以继续使用它与列表中的其他成员进行比较.

As for what's going on, Reduce() accumulates as it goes through the list. At first, identical(names_df1, names_df2) are evaluated. If it's true, we want to have it return the same vector evaluated! Then we can keep using it to compare to other members of the list.

最后,如果所有结果都为true,则返回一个字符向量.由于您可能想要逻辑输出,因此使用!is.logical(...)将字符向量转换为布尔值.

Finally, if everything evaluates as true, we get a character vector returned. Since you probably want a logical output, !is.logical(...) is used to turn that character vector into a boolean.

另请参阅此处,因为我受到另一篇文章的启发:

See also here as I was very inspired by another post:

检查是否所有元素R中的列表是相等的

还有我编辑后看到的类似图片:

And a similar one that I saw after my edit:

测试列表中所有成员之间的相等性

这篇关于有没有一种简单的方法来判断存储在一个列表中的许多数据帧是否包含相同的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆