Sergiodiaz53
Sergiodiaz53

Reputation: 1288

Matrix of vectors in r with col/row names and unknown length

I'm trying to create a data structure to store vectors. What I'm looking for is a 3x2 matrix with vectors of different lenght inside.

             front        side 
Original  c(dim=221) c(dim =200)
zscore    c(dim=221) c(dim =200)
smoothed  c(dim=221) c(dim =200)

I have tried doing:

dataset <- array(dim=c(3,2))
rownames(dataset) <- c("original","zscores","smoothed")
colnames(dataset) <- c("front", "side")

dataset["original", "side"] <- myNumericVectorOfLength221
dataset["original", "front"] <- myNumericVectorOfLength200

But it throws an error of "not the same size". A three dimensional array like: dataset <- array(dim=c(3,2,221)) didn't work because of the differences of length and if I create a matrix of vectors like (dataset["original", "side"] <- list(c(1,2,3))) I lose the col/rownames.

Is there any solution that fits my idea? Thanks in advance.

Upvotes: 1

Views: 301

Answers (2)

digEmAll
digEmAll

Reputation: 57210

You can create a multi-dimensional list, e.g. :

# prepare some random vectors with different lengths
myNumericVectorOfLength221 <- rnorm(221)
myNumericVectorOfLength200 <- rnorm(220)

# create a multi dimensional list
dataset <- array(list(),dim=c(3,2))
rownames(dataset) <- c("original","zscores","smoothed")
colnames(dataset) <- c("front", "side")

# fill some cells
dataset[["original", "side"]] <- vec10
dataset[["zscores","front"]] <- vec3

# let's see the whole matrix
> dataset
         front     side      
original NULL      Integer,10
zscores  Integer,3 NULL      
smoothed NULL      NULL

# let's get one of the added vector
> dataset[["original", "side"]]
[1]  1  2  3  4  5  6  7  8  9 10

Upvotes: 2

LAP
LAP

Reputation: 6685

You could save your vectors in a list and name the elements of said list.

Either create one list with all vectors

mylist <- list("front_Original" = vector1, "front_zscore" = vector2, ...)

or create sublists for your factors

mylist2 <- list("front" = list("Original" = vector1, "zscore" = vector2, ...), 
               "side" = list("Original" = vector3, "zscore" = vector4))

List elements can be of different classes and dimensions, therefore you would not run into any problems this way. Refering to a list works similarly to a data.frame, so you could call a certain vector of mylist2 with mylist2$front$Original or with mylist2[[1]][[1]].

Upvotes: 1

Related Questions