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.
From R base functionality, we have colnames() and names() functions that can be used to rename columns from the list. These functions are used to set or get the names of a dataframe object. You can also use setnames() to change old column names with new columns from the list.
The list can be created using list() function in R. Named list is also created with the same function by specifying the names of the elements to access them. Named list can also be created using names() function to specify the names of elements after defining the list.
To rename an object or variable in R, just copy the data. frame variable to another variable by using the assignment operator (<- or =) and remove the existing variable using rm() function.
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:
lapply
to sapply
.as.list
call.Accessing its elements by name is fairly intuitive:
myvec <- setNames(sapply(mylist,`[[`,2),sapply(mylist,`[[`,1))
myvec["aa"]
# aa
# 2
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))
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