I am new in R and I have a task to create list of lists.
I tried this:
newl <- list()
newl <- append(newl, list(a = 1, b = "x"))
newl <- append(newl, list(a = 15, b = "y"))
newl <- append(newl, list(a = 10, b = "z"))
But append
works like extend
Python function:
$a
[1] 1
$b
[1] "x"
$a
[1] 15
$b
[1] "y"
$a
[1] 10
$b
[1] "z"
I want to get something like this:
[[1]]
$a
[1] 1
$b
[1] "x"
[[2]]
$a
[1] 15
$b
[1] "y"
[[3]]
$a
[1] 10
$b
[1] "z"
Also I want to have an opportunity to sort elements of my list of lists by parameter (for example, by a
). It would look like this:
[[1]]
$a
[1] 1
$b
[1] "x"
[[2]]
$a
[1] 10
$b
[1] "z"
[[3]]
$a
[1] 15
$b
[1] "y"
Also it's important for me to have elements different types inside lists ( int
and string
in the example). In real task it would be function
, vector
, double
and matrix
.
Maybe I need to choose another data type to solve my problem?
Actually you are already close to your desired output, but you may need another list()
within append
, eg,
newl <- list()
newl <- append(newl, list(list(a = 1, b = "x")))
newl <- append(newl, list(list(a = 15, b = "y")))
newl <- append(newl, list(list(a = 10, b = "z")))
such that
> newl
[[1]]
[[1]]$a
[1] 1
[[1]]$b
[1] "x"
[[2]]
[[2]]$a
[1] 15
[[2]]$b
[1] "y"
[[3]]
[[3]]$a
[1] 10
[[3]]$b
[1] "z"
If you want to sort by $a
, you can try
> newl[order(sapply(newl, `[[`, "a"))]
[[1]]
[[1]]$a
[1] 1
[[1]]$b
[1] "x"
[[2]]
[[2]]$a
[1] 10
[[2]]$b
[1] "z"
[[3]]
[[3]]$a
[1] 15
[[3]]$b
[1] "y"
We could do a split
lst1 <- unname(split(newl, as.integer(gl(length(newl), 2, length(newl)))))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.