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

Seb*_*_aj 4 r class lapply dataframe 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))
Run Code Online (Sandbox Code Playgroud)

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

All.list <- list(m1,m2,m3)
Run Code Online (Sandbox Code Playgroud)

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

在此处输入图片说明

Sam*_*rke 5

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
Run Code Online (Sandbox Code Playgroud)

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

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

  • 在比较大量列名称时,此功能对于疲劳的眼睛非常有帮助。拼写上的细微差别给我带来了很大的痛苦,例如,两个数据框中的“Reason_Exclusion”与“Reason_Exclusion”的关系超过“30列”。多谢! (2认同)

小智 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
Run Code Online (Sandbox Code Playgroud)