Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 670
Donkeykongy Avatar asked Mar 11 '23 02:03

Donkeykongy


2 Answers

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
like image 194
RHertel Avatar answered Mar 25 '23 06:03

RHertel


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
like image 32
Roland Avatar answered Mar 25 '23 06:03

Roland