How can I get the last item in every list from a column of lists in R?
I have a column of lists in a dataframe in R that I got from simply splitting pagepaths by "/".
search_console_data$page_title_ <- str_split(search_console_data$page, "/")
I'm wondering if there is a straightforward way to derive the last item from each list into a seperate column or the same one. I'm looking to isolate the page title from url. The dataframe looks like this:
1 | page_title_ |
---|---|
a | c("https:", "", "www.x.com", "") |
b | c("https:", "", "www.y.com", "") |
I've seen solutions like this:
rev(x)[1]
x[length(x)]
and wasn't sure how to apply correctly. Thanks in advance!
Solution 1:
As it is a list
, use lapply/sapply/map
to loop over the list
and get the last
df1$new <- sapply(df1$page_title_, tail, 1)
If the last element is blank (""
), subset to return the non-blank last element
df1$new <- sapply(df1$page_title_, \(x) tail(x[x != ""], 1))
Or using tidyverse
library(dplyr)
library(purrr)
df1 <- df1 %>%
mutate(new = map_chr(page_title_, last))
non-blank last element
df1 <- df1 %>%
mutate(new = map_chr(page_title_, ~ last(.x[.x != ""])))