Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Create Vector of Vector In R

Tags:

I have input data that contain lines like this:

-0.438185 -0.766791  0.695282
0.759100  0.034400  0.524807

How can I create a data structure in R that looks like this:

[[1]]
  [1] -0.438185 -0.766791  0.695282 
[[2]]
  [1]  0.759100  0.034400  0.524807 
like image 217
neversaint Avatar asked Jul 05 '10 12:07

neversaint


People also ask

Can I make a vector of vectors in R?

Create vector in RVectors in R can be created using the c function, that is used for object concatenation. You can save in memory a vector by assigning it a name with the <- operator. Vectors can also be non-numeric. Hence, you can create vectors with characters, logical objects or other types of data objects.

How do I combine vectors in R?

The concatenation of vectors can be done by using combination function c. For example, if we have three vectors x, y, z then the concatenation of these vectors can be done as c(x,y,z). Also, we can concatenate different types of vectors at the same time using the same same function.


2 Answers

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.

like image 123
Stompchicken Avatar answered Sep 20 '22 04:09

Stompchicken


Supposing your data is in the form of a dataframe named, say, df :

library(plyr)
alply(as.matrix(df),1,"[")

gives

$`1`
       V1        V2        V3 
-0.438185 -0.766791  0.695282 

$`2`
      V1       V2       V3 
0.759100 0.034400 0.524807 
like image 45
George Dontas Avatar answered Sep 21 '22 04:09

George Dontas