Gianni
Gianni

Reputation: 63

Change list items to name R

I have a lot of lists that look like this

:List of 73
..$ :List of 2
.. ..$: chr "aaaa"
.. ..$: num 2
..$ :List of 2
.. ..$: chr "cccc"
.. ..$: num 7
..$ :List of 2
.. ..$: chr "dddd"
.. ..$: num 5
..$ :List of 2
.. ..$: chr "bbbb"
.. ..$: num 6

et cetera for 73 times

So there are 73 lists within the list. And each part of those lists contain of two items. But in fact it is one item and the second itemis the value. How can I change the list in an automated way so that it looks something like this:

:List of 73
$ aaaa: num 2
$ cccc: num 7
$ dddd: num 5
$ bbbb: num 6

et cetera for 73 times

I have a lot of lists looking like this, but each time the "aaaa" is on a different place, so changing manually is very time consuming.

Upvotes: 6

Views: 1626

Answers (2)

Frank
Frank

Reputation: 66819

For each element x of mylist, you can access the first sublist with x[[1]]; and the second with x[[2]]. This function can also be called as `[[`(x,i) where i is the number of the sublist.

mylist    <- list(list("aa",2),list("cc",7))
str(mylist)
# List of 2
#  $ :List of 2
#   ..$ : chr "aa"
#   ..$ : num 2
#  $ :List of 2
#   ..$ : chr "cc"
#   ..$ : num 7
mynewlist <- setNames(lapply(mylist,`[[`,2),sapply(mylist,`[[`,1))
str(mynewlist)
# List of 2
#  $ aa: num 2
#  $ cc: num 7

setNames(x,xnames) just returns x with its elements labeled with xnames.


Not using a list. You probably do not need a list and can work with a vector, which is simpler:

  • In my answer, switch the lapply to sapply.
  • In ColonelBeauvel's, remove the as.list call.

Accessing its elements by name is fairly intuitive:

myvec <- setNames(sapply(mylist,`[[`,2),sapply(mylist,`[[`,1))
myvec["aa"]
# aa 
#  2 

Upvotes: 6

Colonel Beauvel
Colonel Beauvel

Reputation: 31171

I would rather use an approach without lapply. If lst is your initial list:

x = unlist(lst)
setNames(as.list(as.numeric(x[seq(2, length(x),2)])),x[seq(1, length(x),2)])

#$aaaa
#[1] 2

#$cccc
#[1] 7

Data:

lst=list(list('aaaa',2), list('cccc',7))

Upvotes: 1

Related Questions