开发者

How To Create Vector of Vector In R

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开发者_C百科 


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.


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 


If it is read from a file, say data.txt, it can be done this way:

lapply(readLines('data.txt'),function(x) as.numeric(strsplit(x,' +')[[1]]))


StompChicken is right, just do it with a list. Though I´d like to add a little trick that might help you learning from existing structures:

 dput(dframe) 

outputs some code to create the respective data.frame or vector. Try this with whatever vector, frame or list and you see how it´s been created, e.g.:

x= c(1,2,3,4)
dput(x)

echos c(1,2,3,4)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜