【问题标题】:Convert list of raw-vectors in dataframe转换数据框中的原始向量列表
【发布时间】:2021-09-24 02:42:07
【问题描述】:

我有一个名为“输出”的原始向量列表。类似的东西:

[1] 58 0a 00 00 00 03 00 04 00 03 00 03 05 00 00 00 00 05 55 54 46 2d 38 00 00 00 fe
[1] 58 0a 00 00 00 03 00 04 00 03 00 03 05 00 00 00 00 05 55 54 46 2d 38 00 01 03 19 00 00 04 02 00 00 00 01 00 04 00 09 00 00 00 04 6d 65 74 61 00 00 02 13 00 00 00 03 00 00 00 10 00 00 00 01 00
[1] ...

它们有不同的长度,属于“原始”类型。

我需要一个数据框,每个单元格中有一个向量:

ID vectors
1 58 0a 00 00 00 03 00 04 00 03 00 03 05 00 00 00 00 05 55 54 46 2d 38 00 00 00 fe
2 58 0a 00 00 00 03 00 04 00 03 00 03 05 00 00 00 00 05 55 54 46 2d 38 00 01 03 19 00 00 04 02 00 00 00 01 00 04 00 09 00 00 00 04 6d 65 74 61 00 00 02 13 00 00 00 03 00 00 00 10 00 00 00 01 00

我试过这个:

as.data.frame(output) 
#Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE,  : 
  arguments imply differing number of rows: 27, 3132, 4141, 4267, 3701, 3943, 5200

df <- data.frame(matrix(unlist(output), nrow=length(output)))
#Warning message:
In matrix(unlist(output), nrow = length(output)) :
  data length [32954] is not a sub-multiple or multiple of the number of rows [14]

有没有办法解决我的问题?

【问题讨论】:

    标签: r dataframe vector raw


    【解决方案1】:

    创建data.frame时必须使用I

    output <- list(raw(2), raw(3))
    DF <- data.frame(ID=1:2, vectors = I(output))
    
    str(DF)
    #'data.frame':   2 obs. of  2 variables:
    # $ ID     : int  1 2
    # $ vectors:List of 2
    #  ..$ : raw  00 00
    #  ..$ : raw  00 00 00
    #  ..- attr(*, "class")= chr "AsIs"
    
    DF
    #DF
    #  ID    vectors
    #1  1     00, 00
    #2  2 00, 00, 00
    

    【讨论】:

    • 哦,谢谢!以前从未见过 I() 函数......但它的效果很好!
    • 当我以这种方式创建数据框时,我在向量的单元格中发现了一个问题。它应该包含类似:58 0a 00 00 00 03 00 04 00 03 00 03 05 00 00 00 00 05 55 54 46 2d 38 00 但我现在有:as.raw(c(0x58, 0x0a, 0x00, 0x00, 0x00, 0x03, 0x00))
    • 你发现了什么问题?
    • 数据框 str(DF) 的结构是相同的,但如果我用 DF 打开数据框,则向量列中的单元格包含 as.raw(c(0x58...)) 58 0a 00...
    • DF$vectors 应该得到与output 相同的结果。
    【解决方案2】:

    这也可以通过tibble完成

    library(tibble)
    output <- list(raw(2), raw(3))
    tibble(ID = 1:2, vectors = output)
    # A tibble: 2 x 2
         ID vectors  
      <int> <list>   
    1     1 <raw [2]>
    2     2 <raw [3]>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-25
      • 2021-01-18
      • 2015-04-01
      • 2018-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多