Home > Software engineering >  How to extract values from list?
How to extract values from list?

Time:05-02

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\")

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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.

  •  Tags:  
  • r
  • Related