How to Get Last Subelement of Every Element of a List

How to get last subelement of every element of a list?

We can use lapply and tail:

x <- list(a = 1:5, b = 1:10, d = 9:11)
last_elems <- lapply(x, tail, n = 1L)

As pointed out in the comments, to obtain a numeric vector instead of a one-element list, vapply is a good choice:

last_elems <- vapply(x, tail, n = 1L, FUN.VALUE = numeric(1))

R: Access the last subelement of each element in a list

We can do this with base R. Either using sub

sub(".*__", "", x)
#[1] "Mike" "Paul" "Daniel" "Martha" "John" "Laura"

or with strsplit, we get the last element with tail

sapply(strsplit(x, '__'), tail, 1)
#[1] "Mike" "Paul" "Daniel" "Martha" "John" "Laura"

Or to find the position, we can use gregexpr and then extract using substring

substring(x, sapply(gregexpr("[^__]+", x), tail, 1))
#[1] "Mike" "Paul" "Daniel" "Martha" "John" "Laura"

Or with stri_extract_last

library(stringi)
stri_extract_last(x, regex="[^__]+")
#[1] "Mike" "Paul" "Daniel" "Martha" "John" "Laura"

Extract second subelement of every element in a list while ignoring NA's in sapply in R

This should do what you want:

sapply(mylist,function(x) x[2])

How to get the second sub element of every element in a list

To select the second element of each list item:

R> sapply(df$suf, "[[", 2)
[1] "00" "01" "02" "00" "01" "02" "21" "01" "03"

An alternative approach using regular expressions:

df$pre <- sub("^([A-Z]+)[0-9]+", "\\1", df$lab)
df$suf <- sub("^[A-Z]+([0-9]+)", "\\1", df$lab)

Extract the first, second, third , … sub-element from a list in R and store as list

Yes

lapply(1:15, function(i) sapply(list_data, '[', i))

How do you extract elements beside sub-elements from a list in R?

Given

List <- list(
list(name="A",params=list(param_1=5, param_2=list(param_2_1=10,param_2_2=11))),
list(name="B",params=list(param_1=6, param_2=list(param_2_1=12,param_2_2=13)))
)

then

> data.frame(do.call(rbind,lapply(List,unlist)))
name params.param_1 params.param_2.param_2_1 params.param_2.param_2_2
1 A 5 10 11
2 B 6 12 13

In a list of lists how to get all the items except the last one for each list?

This is the shortest and easiest way:

output = [l[:-1] for l in x]

It is called a list comprehension .

How to get the second to last element in a Vector in R

It seems you want to leave one element from the vector A. You can simply write B=tail(A,-1)
where -1 leaves the first element.



Related Topics



Leave a reply



Submit