1

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?

2 Answers 2

2

Actually you are already close to your desired output, but you may need another list() within append, e.g.,

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" 
Sign up to request clarification or add additional context in comments.

Comments

0

We could do a split

lst1 <- unname(split(newl, as.integer(gl(length(newl), 2, length(newl))))) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.