'How to extract values from list?

I have a list which looks like the following:

list(Element1 =  c('ra12345', 'ra13467'),
     Element2 = c('ra3467', 'ra5643', 'ra55959'))

I want to run through each element in the list, remove the 'ra' to just leave the integers and then to be able to access each integer individually. I.e. for element 1, I want to be able to access 12345 and 13467 individually, however, I don't know how to do so.

I've tried:

for (I in length(listName)) {
 variable <- gsub("rs", "", listName[i])

}

But this returns: c(\"12345\", \"ra13467\")

r


Solution 1:[1]

A possible solution, based on tidyverse:

library(tidyverse)

l <- list(Element1 = c('ra12345','ra13467'), Element2 = c('ra3467', 'ra5643', 'ra55959'))

map(l, parse_number)

#> $Element1
#> [1] 12345 13467
#> 
#> $Element2
#> [1]  3467  5643 55959

Solution 2:[2]

Here is an option in base R.

l <- list(Element1 = c('ra12345','ra13467'),
          Element2 = c('ra3467', 'ra5643', 'ra55959'))

l2 <- lapply(l, function(x) as.numeric(gsub("ra", "", x, fixed = TRUE)))
l2
# $Element1
# [1] 12345 13467
# 
# $Element2
# [1]  3467  5643 55959

str(l2)
# List of 2
#  $ Element1: num [1:2] 12345 13467
#  $ Element2: num [1:3] 3467 5643 55959

Solution 3:[3]

list(Element1 =  c('ra12345', 'ra13467'),
     Element2 = c('ra3467', 'ra5643', 'ra55959')) %>% 
  purrr::map(readr::parse_number())

Result:

$Element1
[1] 12345 13467

$Element2
[1]  3467  5643 55959

The only difference to Paul's solution in the end is that extract_numeric() returns numeric values, while str_remove returns a character value.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Adam
Solution 3