在R中比较不同数据框的列名

5

我目前正在尝试在进行任何转换和计算之前比较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

2个回答

6
尝试使用janitor软件包中的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

它接受列表和/或单个命名的数据帧,即compare_df_cols(m1,m2,m3)。免责声明:我维护janitor包,该函数最近被添加到其中 - 在此发布,因为它正好解决了这种情况。

2
这个函数在比较大量列名时对疲劳的眼睛非常有帮助。拼写上的轻微差异给我带来了很多痛苦,例如在两个具有> 30列的数据框中,Reason_ExcludeReason_Exclusion之间的区别。非常感谢! - Matthew J. Oldach

1

我认为最简单的方法是定义一个函数,然后使用lapply和dplyr的组合来获得你想要的结果。以下是我的做法。

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

All.list <- list(m1,m2,m3)


##Define a function to get variable names and types
my_function <- function(data_frame){
  require(dplyr)
  x <- tibble(`var_name` = colnames(data_frame),
              `var_type` = sapply(data_frame, class))
  return(x)
}


target <- lapply(1:length(All.list),function(i)my_function(All.list[[i]]) %>% 
mutate(element =i)) %>%
  bind_rows() %>%
  spread(element, var_type)

target

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接