6

I'm pretty new to R, and was wondering if there is a way to store vectors in a data frame such that each entry of the data frame is a vector.

I want to assign the entry to a vector, and be able to change it later:

df[2,]$Value <- c(1,2,0)
df[3,]$Value <- c(0,0,1)
df[3,]$Value <- df[3,]$Value + c(2,4,4)

But can only make this work as replacing 3 different entries in the data frame. Does anyone know if this is possible?

df: 
      V1    V2     V3 
1 c(1,2) c(2,3) c(0,0) 
2 c(1,1) c(0,0) c(2,2)
user1428668
  • 147
  • 1
  • 2
  • 6

1 Answers1

3

You cannot have a 3D data frame. You can achieve this many ways but the easiest one to explain conceptually would probably be to have a list within a list:

> entries <- list(V1=list(c(1,2), c(1,1)), V2=list(c(2,3), c(0,0)), V3=list(c(0,0),c(2,2)))
> entries
$V1
$V1[[1]]
[1] 1 2

$V1[[2]]
[1] 1 1


$V2
$V2[[1]]
[1] 2 3

$V2[[2]]
[1] 0 0


$V3
$V3[[1]]
[1] 0 0

$V3[[2]]
[1] 2 2

Now lets say you want to change the second entry of V1 you would simply do

entries$V1[[2]] <- c(2,2)

or

entries[[1]][[2]] <- c(2,2)

LostLin
  • 7,762
  • 12
  • 51
  • 73
  • I understand how to replace a row or column; I want to store the vectors in the data frame, one vector as each entry: df: V1 V2 V3 1 c(1,2) c(2,3) c(0,0) 2 c(1,1) c(0,0) c(2,2) – user1428668 Jun 21 '12 at 18:43
  • what do you mean by entry? do you mean row? – LostLin Jun 21 '12 at 18:44
  • see data frame example in question... Sorry this is so confusing! – user1428668 Jun 21 '12 at 18:46
  • Well, you *can* since `data.frames` are `lists`, but maybe not easily. See the `dput` in [this question](http://stackoverflow.com/questions/11125131/most-efficient-way-to-replace-lowest-list-values-in-dataframe-in-r) – GSee Jun 21 '12 at 19:14
  • 1
    or, `do.call(rbind, list(V1=list(c(1,2), c(1,1)), V2=list(c(2,3), c(0,0)), V3=list(c(0,0),c(2,2))))` – GSee Jun 22 '12 at 06:20