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
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.
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.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With