Is it possible to store an vector inside a dataframe cell?

Viewed 2683

I´m trying to create an dataframe which is holding an ID and an numeric vector with an unknown count of grades per row, but I don´t know how to do this.

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

Later I am trying to add a new row to the dataframe using:

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

How is it possible to store an vector of numeric values inside a single dataframe cell?

2 Answers

Yes of course :) A data.frame is a list and therefore you can nest difference data structures inside it:

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

I agree with Stephen Henderson's comment that you shouldn't use list-columns unless you are absolutely sure that they are the best way to solve your specific problem. That being said, if you do decide to use list columns, you might want to consider using tibbles instead of data frames. Tibbles are an 'upgrade' to regular data frames. They are part of the tidyverse and come in the tibble package.

Tibbles make it easy to create list columns:

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]>

Moreover, you can "pack" and "unpack" list-columns using the commands nest and unnest from the tidyr package. For example:

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

For more information about tibbles you can consult this vignette.

Related