将表转换为数据框

scs*_*scs 0 r dataframe

我想转换一个表,一个数据帧.

例:

tbl <- structure(c(1L, 0L, 0L, 0L, 1L, 0L, 0L, 0L), .Dim = c(4L, 2L), .Dimnames = structure(list(
c("1", "2", "3", "4"), colNames = c("2013 3", "2014 12")), .Names = c("", "colNames")), class = "table")

colNames
     2013 3 2014 12
1      1       1
2      0       0
3      0       0
4      0       0
Run Code Online (Sandbox Code Playgroud)

转换为数据框会导致完全不同的数据结构.为什么?

as.data.frame(tbl)

Var1 colNames Freq
1    1   2013 3    1
2    2   2013 3    0
3    3   2013 3    0
4    4   2013 3    0
5    1  2014 12    1
6    2  2014 12    0
7    3  2014 12    0
8    4  2014 12    0
Run Code Online (Sandbox Code Playgroud)

hrb*_*str 6

那么,"为什么"确切原因是这是源代码(只需在R控制台中输入该名称,没有其他标点符号在控制台中查看):as.data.frame.table

function(x, row.names = NULL, ..., responseName = "Freq", 
         stringsAsFactors = TRUE, sep = "", base = list(LETTERS))  {

  ex <- quote(
    data.frame(
      do.call(
        "expand.grid", 
        c(
          dimnames(provideDimnames(x, sep = sep, base = base)), 
          KEEP.OUT.ATTRS = FALSE, 
          stringsAsFactors = stringsAsFactors)
      ), 
      Freq = c(x), row.names = row.names)
  )
  names(ex)[3L] <- responseName
  eval(ex)

}
Run Code Online (Sandbox Code Playgroud)

最终,你有什么:

tbl <- structure(
  c(1L, 0L, 0L, 0L, 1L, 0L, 0L, 0L), 
  .Dim = c(4L, 2L), 
  .Dimnames = structure(
    list(
      c("1", "2", "3", "4"), 
      colNames = c("2013 3", "2014 12")
    ), 
    .Names = c("", "colNames")
  ), 
  class = "table"
)
Run Code Online (Sandbox Code Playgroud)

integer具有某些属性的向量.当你在R控制台中键入tbl并按下<ENTER>它时,它会调用print.table()(print.table在R控制台中没有其他标点符号输入以查看其来源)它会通过一些箍来打印你所看到的"矩形"数据结构.

要获得所需的结果,只需执行打印功能最终执行的操作(以非直截了当的方式):

as.data.frame.matrix(tbl)
Run Code Online (Sandbox Code Playgroud)

或使用tidyverse习语:

as.data.frame(tbl) %>% 
  tidyr::spread(colNames, Freq)
##   Var1 2013 3 2014 12
## 1    1      1       1
## 2    2      0       0
## 3    3      0       0
## 4    4      0       0
Run Code Online (Sandbox Code Playgroud)