r - 比较 R 中各种数据框的列名

标签 r class dataframe lapply sapply

我目前正在尝试在进行任何转换和计算之前比较 R 中各种数据框的列类和名称。
我的代码如下所示:

library(dplyr)
m1 <-  mtcars
m2 <-  mtcars %>% mutate(cyl = factor(cyl), xxxx1 = factor(cyl))
m3 <-  mtcars %>% mutate(cyl = factor(cyl), xxxx2 = factor(cyl))

out <-  cbind(sapply(m1, class), sapply(m2, class), sapply(m3, class))

如果有人可以为存储在列表中的数据帧解决这个问题,那就太好了。我所有的数据帧目前都存储在一个列表中,以便于处理。
All.list <- list(m1,m2,m3)

我期望输出以矩阵形式显示,如数据框“out”中所示。 “out”中的输出是不可取的,因为它是不正确的。我希望输出更多如下:

enter image description here

最佳答案

试试 compare_df_cols()从看门人包:

library(janitor)
compare_df_cols(All.list)

#>    column_name All.list_1 All.list_2 All.list_3
#> 1           am    numeric    numeric    numeric
#> 2         carb    numeric    numeric    numeric
#> 3          cyl    numeric     factor     factor
#> 4         disp    numeric    numeric    numeric
#> 5         drat    numeric    numeric    numeric
#> 6         gear    numeric    numeric    numeric
#> 7           hp    numeric    numeric    numeric
#> 8          mpg    numeric    numeric    numeric
#> 9         qsec    numeric    numeric    numeric
#> 10          vs    numeric    numeric    numeric
#> 11          wt    numeric    numeric    numeric
#> 12       xxxx1       <NA>     factor       <NA>
#> 13       xxxx2       <NA>       <NA>     factor

它接受列表和/或名为 data.frames 的个人,即 compare_df_cols(m1, m2, m3) .

免责声明:我维护最近添加了此功能的管理员包 - 将其发布在这里,因为它正好解决了这个用例。

关于r - 比较 R 中各种数据框的列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53264993/

相关文章:

r - 如何保存拟合的R模型以备后用

r - 在 R 中为 ggplot 预设绘图选项的好方法是什么

C++ - 类中的私有(private)变量

r - 根据 R 中另一个 df 中的一行中的多个值有条件地填充一个 df 中的列的更好方法

python - 使用 groupby 的结果过滤 pandas 数据框

r - 计算 R 中唯一的分类变量对

r - 无法将参数传递给自己的函数中的函数

python - 类似于 Python 中的 Pojo 类

swift - NSArrayController 排序 : "this class is not key value coding-compliant for the key"

python - 如何使用 python2.7.14 在不覆盖 excel 文件中存在的先前数据的情况下使用不同的数据框更新相同的 excel 表?