Donkeykongy
Donkeykongy

Reputation: 135

storing a vector in a matrix in r with unknown vector length

Hi there i was wondering if is there a way to store a vector into an array or matrix. for example,

array1<-array(dim=c(1,2))
vector1<-as.vector(1:5)
vector2<-as.vector(6:10)
array1[1,1]<-vector1
array1[1,2]<-vector2

so that when i call for

array1[1,1]

i will receive

[1] 1 2 3 4 5

I've tried doing what i did above and what i get the error

 number of items to replace is not a multiple of replacement length

is there a way to get around this?

also, the problem that i face is that i do not know the vector length and that the vectors could have different length as well.

i.e vector 1 can be length of 6 and vector 2 can be a length of 7.

thanks!

Upvotes: 4

Views: 2807

Answers (2)

Roland
Roland

Reputation: 132676

You can use a matrix of lists:

m <- matrix(list(), 2, 2)
m[1,1][[1]] <- 1:2
m[1,2][[1]] <- 1:3
m[2,1][[1]] <- 1:4
m[2,2][[1]] <- 1:5
m
#     [,1]      [,2]     
#[1,] Integer,2 Integer,3
#[2,] Integer,4 Integer,5

m[1, 2]
#[[1]]
#[1] 1 2 3

m[1, 2][[1]]
#[1] 1 2 3

Upvotes: 3

RHertel
RHertel

Reputation: 23788

Try with a list:

my_list <- list()
my_list[[1]] <- c(1:5)
my_list[[2]] <- c(6:11)

A list allows you to store vectors of varying length. The vectors can be retrieved by addressing the element of the list:

> my_list[[1]]
#[1] 1 2 3 4 5

Upvotes: 4

Related Questions