Saving a vector in a matrix with respect to r with unknown vector length

Hi, I was wondering if there is a way to save the vector to an array or matrix. eg,

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 you call

array1[1,1]

I get

[1] 1 2 3 4 5

I tried to do what I did above and that I got an error

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

Is there any way around this?

also the problem that I am facing is that I do not know the length of the vector and that the vectors can have a different length.

ie vector 1 can be length 6, and vector 2 can be length 7.

thank!

+4
source share
2 answers

Try with a list:

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

The list allows you to store vectors of various lengths. Vectors can be obtained by accessing the list item:

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

:

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
+1

Source: https://habr.com/ru/post/1654990/


All Articles