Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing a list within a data frame element in R

I want to create a data structure in the form of

Start, End, Elements
  3  , 6  ,  {4,5}
  4 ,  10 ,  {7,8,9}
   ....

In words, I am moving a ball along a line. The "start" represents the left most position of the ball and the "End" represents the right most. The "Elements" means I somehow find those positions special. What is the best data structure to use when the number of elements can grow very large? The only thing I can think of is a data frame where the 3rd column is an appropriately formatted string. I would then have to parse the string if I wanted to look at each number in the set. Is there a better data format that R has or is that about it?

Thanks!

like image 879
user1357015 Avatar asked Apr 12 '13 20:04

user1357015


1 Answers

The option mentioned in my comment, i.e. simply using a list for one of the columns:

dat <- data.frame(Start = 3:4, End = c(6,10))
> dat
  Start End
1     3   6
2     4  10
> dat$Elements <- list(4:5,7:9)
> dat
  Start End Elements
1     3   6     4, 5
2     4  10  7, 8, 9

You could also of course ditch data frames entirely and simply use a plain old list (which might make more sense in a lot of cases, anyway):

list(list(Start = 3,End = 6, Elements = 4:5),list(Start = 4,End = 10,Elements = 7:9))
[[1]]
[[1]]$Start
[1] 3

[[1]]$End
[1] 6

[[1]]$Elements
[1] 4 5


[[2]]
[[2]]$Start
[1] 4

[[2]]$End
[1] 10

[[2]]$Elements
[1] 7 8 9
like image 174
joran Avatar answered Oct 02 '22 07:10

joran