代码之家  ›  专栏  ›  技术社区  ›  JohnDizzle

是否可以在数据帧单元中存储矢量?

r
  •  2
  • JohnDizzle  · 技术社区  · 6 年前

    我试图创建一个数据帧,其中包含一个ID和一个数值向量,每行成绩计数未知,但我不知道如何做到这一点。

    studentmean <-
        data.frame(
          Student = character(),
          Grades = c(0),
          stringsAsFactors = FALSE
        )
    

    稍后,我尝试使用

    gradeList <- getGradesOfStudent(data$ResultFrame, matriculationNumber)$Grades
        studentmean[nrow(studentmean) + 1, ] = list(as.character(matriculationNumber), gradeList
    

    如何在单个数据帧单元中存储数值向量?

    2 回复  |  直到 6 年前
        1
  •  2
  •   A. Stam    6 年前

    我同意斯蒂芬·亨德森的观点,即除非你确信列表列是解决你的特定问题的最佳方法,否则你不应该使用列表列。也就是说,如果您确实决定使用列表列,那么您可能会考虑使用隐藏的而不是数据帧。Tibbles是对常规数据帧的“升级”。它们是潮歌的一部分 tibble 包裹。

    Tibbles使创建列表列变得容易:

    tibble(x = 1:3, y = list(1:5, 1:10, 1:20))
    
    #> # A tibble: 3 x 2
    #>       x y         
    #>   <int> <list>    
    #> 1     1 <int [5]> 
    #> 2     2 <int [10]>
    #> 3     3 <int [20]>
    

    此外,您可以使用命令“打包”和“解包”列表列 nest unnest tidyr 包裹。例如:

    df <- tibble(
      x = 1:3,
      y = c("a", "d,e,f", "g,h")
    )
    df %>%
      transform(y = strsplit(y, ",")) %>%
      unnest(y)
    

    有关藏书的更多信息,请参阅 vignette .

        2
  •  3
  •   trosendal    6 年前

    当然可以:)A data.frame 是一个 list 因此,您可以在其中嵌套不同的数据结构:

    df <- data.frame(a = c(1,2,3), b = c("a", "b", "c"))
    df$c <- list(c(1, 2, 3), c(4,5,6), c(7,8,9))
    
    > str(df)
    'data.frame':   3 obs. of  3 variables:
     $ a: num  1 2 3
     $ b: Factor w/ 3 levels "a","b","c": 1 2 3
     $ c:List of 3
      ..$ : num  1 2 3
      ..$ : num  4 5 6
      ..$ : num  7 8 9