【问题标题】:Determine the data types of a data frame's columns确定数据框列的数据类型
【发布时间】:2014-02-03 04:50:40
【问题描述】:

我正在使用 R 并已使用 read.csv() 将数据加载到数据框中。如何确定数据框中每一列的数据类型?

【问题讨论】:

  • 以编程方式(例如sapply(..., class)) 或交互方式(例如str(...))或两者兼而有之?通常以编程方式进行更具可扩展性,然后您可以任意Filter(...) 整数、字符、因子等的列表. 或者您可以使用grep/greplnames(...) 推断列类型(如果它们遵循任何命名约定)
  • @smci:我在最初的问题中没有要求“以编程方式”。我不知道你为什么要改变我问题的整个性质。
  • 好的,已回滚。它并没有改变整个性质,它在两个方向之一上澄清了它。使用 str(...) 的交互式方法不可扩展,并且在

标签: r dataframe types


【解决方案1】:

您最好的选择是使用?str()。为了探索一些例子,让我们做一些数据:

set.seed(3221)  # this makes the example exactly reproducible
my.data <- data.frame(y=rnorm(5), 
                      x1=c(1:5), 
                      x2=c(TRUE, TRUE, FALSE, FALSE, FALSE),
                      X3=letters[1:5])

@Wilmer E Henao H 的解决方案非常精简:

sapply(my.data, class)
        y        x1        x2        X3 
"numeric" "integer" "logical"  "factor" 

使用str() 可以获得这些信息以及额外的好处(例如您的因子水平和每个变量的前几个值):

str(my.data)
'data.frame':  5 obs. of  4 variables:
$ y : num  1.03 1.599 -0.818 0.872 -2.682
$ x1: int  1 2 3 4 5
$ x2: logi  TRUE TRUE FALSE FALSE FALSE
$ X3: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5

@Gavin Simpson 的方法也很精简,但提供的信息与class() 略有不同:

sapply(my.data, typeof)
       y        x1        x2        X3 
"double" "integer" "logical" "integer"

有关classtypeof 和中间孩子mode 的更多信息,请参阅此出色的SO 线程:A comprehensive survey of the types of things in R. 'mode' and 'class' and 'typeof' are insufficient

【讨论】:

  • 使用R几个月后,我发现str(dataframe)是一目了然确定列类型的最快方法。其他方法需要更多的击键并且不会显示太多信息,但如果列数据类型是其他函数的输入,它们会很有帮助。
  • 嗨,当我使用 apply 而不是 apply 时,它不起作用
  • @DomJo,你为什么要使用apply()?那是为了矩阵。数据框是一种(特殊类型的)列表。
  • 因为 sapply(foo, typeof) 为 Date 对象返回“整数”,所以我使用了 sapply(foo, class)。但是,这可以返回一个列表。所以最后我使用names(foo)[sapply(sapply(foo, class), function(x) { "Date" %in% x })] 来识别foo 中属于“Date”类的所有列。
【解决方案2】:
sapply(yourdataframe, class)

yourdataframe 是您正在使用的数据框的名称

【讨论】:

  • 完美。正是我需要的。
【解决方案3】:

建议

sapply(foo, typeof)

如果您需要数据框中向量的实际类型。 class() 有点不同。

如果您不需要将此信息作为向量获取(即您以后不需要它以编程方式执行其他操作),只需使用str(foo)

在这两种情况下,foo 都将替换为您的数据框的名称。

【讨论】:

    【解决方案4】:

    对于小数据帧:

    library(tidyverse)
    
    as_tibble(mtcars)
    

    为您提供带有数据类型的 df 打印文件

    # A tibble: 32 x 11
         mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
     * <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
     1  21       6  160    110  3.9   2.62  16.5     0     1     4     4
     2  21       6  160    110  3.9   2.88  17.0     0     1     4     4
     3  22.8     4  108     93  3.85  2.32  18.6     1     1     4     1
    

    对于大型数据框:

    glimpse(mtcars)
    

    为您提供数据类型的结构化视图:

    Observations: 32
    Variables: 11
    $ mpg  <dbl> 21.0, 21.0, 22.8, 21.4, 18.7, 18.1, 14.3, 24.4, 22.8, 19.2, 17.8, 16.4, 17....
    $ cyl  <dbl> 6, 6, 4, 6, 8, 6, 8, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 4, 4, 4, 4, 8, 8, 8, 8, ...
    $ disp <dbl> 160.0, 160.0, 108.0, 258.0, 360.0, 225.0, 360.0, 146.7, 140.8, 167.6, 167.6...
    $ hp   <dbl> 110, 110, 93, 110, 175, 105, 245, 62, 95, 123, 123, 180, 180, 180, 205, 215...
    $ drat <dbl> 3.90, 3.90, 3.85, 3.08, 3.15, 2.76, 3.21, 3.69, 3.92, 3.92, 3.92, 3.07, 3.0...
    $ wt   <dbl> 2.620, 2.875, 2.320, 3.215, 3.440, 3.460, 3.570, 3.190, 3.150, 3.440, 3.440...
    $ qsec <dbl> 16.46, 17.02, 18.61, 19.44, 17.02, 20.22, 15.84, 20.00, 22.90, 18.30, 18.90...
    $ vs   <dbl> 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, ...
    $ am   <dbl> 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, ...
    $ gear <dbl> 4, 4, 4, 3, 3, 3, 3, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 4, 4, 4, 3, 3, 3, 3, 3, ...
    $ carb <dbl> 4, 4, 1, 1, 2, 1, 4, 2, 2, 4, 4, 3, 3, 3, 4, 4, 4, 1, 2, 1, 1, 2, 2, 4, 2, ...
    

    获取列的数据类型列表(如上面@Alexandre 所说):

    map(mtcars, class)
    

    给出数据类型列表:

    $mpg
    [1] "numeric"
    
    $cyl
    [1] "numeric"
    
    $disp
    [1] "numeric"
    
    $hp
    [1] "numeric"
    

    更改列的数据类型:

    library(hablar)
    
    mtcars %>% 
      convert(chr(mpg, am),
              int(carb))
    

    mpgam 列转换为字符,将carb 列转换为整数:

    # A tibble: 32 x 11
       mpg     cyl  disp    hp  drat    wt  qsec    vs am     gear  carb
       <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <chr> <dbl> <int>
     1 21        6  160    110  3.9   2.62  16.5     0 1         4     4
     2 21        6  160    110  3.9   2.88  17.0     0 1         4     4
     3 22.8      4  108     93  3.85  2.32  18.6     1 1         4     1
     4 21.4      6  258    110  3.08  3.22  19.4     1 0         3     1
    

    【讨论】:

      【解决方案5】:

      只需将您的数据框传递给以下函数:

      data_types <- function(frame) {
        res <- lapply(frame, class)
        res_frame <- data.frame(unlist(res))
        barplot(table(res_frame), main="Data Types", col="steelblue", ylab="Number of Features")
      }
      

      生成数据框中所有数据类型的图。对于 iris 数据集,我们得到以下信息:

      data_types(iris)
      

      【讨论】:

        【解决方案6】:

        另一种选择是使用 purrr 包的地图功能。

        library(purrr)
        map(df,class)
        

        【讨论】:

          【解决方案7】:

          由于没有说清楚,我就补充一下:

          我正在寻找一种方法来创建一个表格,该表格包含所有数据类型的出现次数

          假设我们有一个data.frame,其中包含两个数字和一个逻辑列

          dta <- data.frame(a = c(1,2,3), 
                            b = c(4,5,6), 
                            c = c(TRUE, FALSE, TRUE))
          

          你可以用它来总结每种数据类型的列数

          table(unlist(lapply(dta, class)))
          # logical numeric 
          #       1       2 
          

          如果您有很多列并且想要快速了解一下,这会非常方便。

          致谢:此解决方案的灵感来自 the answer of @Cybernetic

          【讨论】:

            【解决方案8】:

            这是helpRFunctions 包中的一个函数,它将返回数据框中所有各种数据类型的列表,以及与该类型关联的特定变量名称。

            install.package('devtools') # Only needed if you dont have this installed.
            library(devtools)
            install_github('adam-m-mcelhinney/helpRFunctions')
            library(helpRFunctions)
            my.data <- data.frame(y=rnorm(5), 
                              x1=c(1:5), 
                              x2=c(TRUE, TRUE, FALSE, FALSE, FALSE),
                              X3=letters[1:5])
            t <- list.df.var.types(my.data)
            t$factor
            t$integer
            t$logical
            t$numeric
            

            然后您可以执行var(my.data[t$numeric]) 之类的操作。

            希望对您有所帮助!

            【讨论】:

            • 值得注意的是,在后台这是lapply(your_data, class),并进行了一些额外的格式化处理。
            【解决方案9】:

            为了方便数据框,这里有一个简单的 base 函数

            col_classes <- function(df) {
              data.frame(
              variable = names(df),
              class = unname(sapply(df, class))
              )
            }
            col_classes(my.data)
              variable     class
            1        y   numeric
            2       x1   integer
            3       x2   logical
            4       X3 character
            

            【讨论】:

              【解决方案10】:

              如果将 csv 文件作为 data.frame(而不是矩阵)导入,也可以使用 summary.default

              summary.default(mtcars)
              
                   Length Class  Mode   
              mpg  32     -none- numeric
              cyl  32     -none- numeric
              disp 32     -none- numeric
              hp   32     -none- numeric
              drat 32     -none- numeric
              wt   32     -none- numeric
              qsec 32     -none- numeric
              vs   32     -none- numeric
              am   32     -none- numeric
              gear 32     -none- numeric
              carb 32     -none- numeric
              

              【讨论】:

                【解决方案11】:

                要获得带有类型和类的漂亮 Tibble:

                  purrr::map2_df(mtcars,names(mtcars), ~ {
                    tibble(
                      field = .y,
                      type = typeof(.x),
                      class_1 = class(.x)[1],
                      class_2 = class(.x)[2]
                    )
                    })
                

                【讨论】:

                  猜你喜欢
                  • 2017-05-06
                  • 1970-01-01
                  • 1970-01-01
                  • 2018-05-25
                  • 1970-01-01
                  • 2015-09-19
                  • 1970-01-01
                  • 1970-01-01
                  • 2014-04-23
                  相关资源
                  最近更新 更多