在各种数据帧中比较R中的列名

问题描述 投票:2回答:2

我目前正在尝试比较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

r class dataframe lapply sapply
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

0
投票

尝试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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.