【问题标题】:Listing variable types using tidyverse使用 tidyverse 列出变量类型
【发布时间】:2021-04-21 13:32:36
【问题描述】:

我正在尝试将大部分我最喜欢的 R 命令转移到 tidyverse。我通常在导入数据后首先检查的第一件事就是每个变量的格式,例如:

data(cars)
sapply(cars, class)

#    speed      dist 
# "numeric" "numeric"

变成:

library(tidyverse)
exam.table %>%
   sapply(class)

#    speed      dist 
# "numeric" "numeric"

那么您将如何将其转置为tidyverse?旧版本是:

t(t(sapply(cars,class)))

#          [,1]     
#    speed "numeric"
#    dist  "numeric"

【问题讨论】:

  • 我不同意使用带有sapply 的管道比将其编写为函数调用更“整洁”。首先,管道不是 tidyverse 独有的,它是独立存在的,并且在 tidyverse 之前存在。其次,sapply 是一个非常基本的 R 函数,没有什么 tidyversey 的地方。使用 tidyverse 函数的目的是避免来自基本 R 函数的陷阱,sapply 有很多陷阱。
  • 对不起,为了简单起见,我已经习惯使用 tidyverse 包和管道内涵 tidyverse 来调用所有内容。如果我通过正确的包名称(即dplyrgglot2magrittr 等)引用每个元素,我的学生会立即燃烧起来。是的,基本 R 命令没有任何问题,但我的学生再次希望尽可能多地使用管道 (doh)。

标签: r tidyverse


【解决方案1】:
cars %>% sapply(class) %>% as.data.frame() %>% rownames_to_column("col")

    col       .
1 speed numeric
2  dist numeric

或者

cars %>% sapply(class) %>% as.data.frame()
            .
speed numeric
dist  numeric

【讨论】:

    【解决方案2】:

    一个非常“整洁”的散文可能是:

    cars %>% map_df(class) %>% t()
          [,1]     
    speed "numeric"
    dist  "numeric"
    

    【讨论】:

      【解决方案3】:

      sapply 的“tidyverse”等价物是purrr::map family of functions。在你的情况下,map_chr:

      map_chr(df, class)
      

      如果您希望将结果放在 data.frame 中,只需将其包装在 tibble 中:

      tibble(cols = names(cars), class = map_chr(cars, class))
      

      ……当然,您也可以为此使用管道符号:

      cars %>% {tibble(col = names(.), class = map_chr(., class))}
      

      或者

      cars %>% map_chr(class) %>% tibble(col = names(.), class = .)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-17
        • 2012-05-09
        • 1970-01-01
        • 2018-09-17
        • 2020-06-18
        • 2018-02-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多