How To Create Vector of Vector In R

Use a list:

> x <- list()
> x[[1]] <- c(-0.438185, -0.766791, 0.695282)
> x[[2]] <- c(-0.759100, 0.034400, 0.524807)

> x
[[1]]
[1] -0.438185 -0.766791  0.695282

[[2]]
[1] -0.759100  0.034400  0.524807

Think of it as a map/dictionary/associative array that is being indexed by an integer.

And if you want to take a string like the one above and turn it into a list of vectors:

> s <- "-0.438185 -0.766791  0.695282\n0.759100  0.034400  0.524807"
> x <- lapply(strsplit(s, "\n")[[1]], function(x) {as.numeric(strsplit(x, '\\s+')[[1]])})
> x
[[1]]
[1] -0.438185 -0.766791 0.695282

[[2]]
[1] 0.759100 0.034400 0.524807

I’m using strsplit to split by newlines, then applying strsplit again to each line. The as.numeric is there to cast from strings to numbers and the [[1]]’s are there because strsplit outputs a list, which we don’t really want.

Leave a Comment