1

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

Julian
  • 6,586
  • 2
  • 9
  • 33
github292929
  • 185
  • 7
  • Regarding the second part of your question, that may be a `[` vs. `[[` thing. If that is the case, this should help: https://stackoverflow.com/questions/1169456/the-difference-between-bracket-and-double-bracket-for-accessing-the-el –  May 02 '22 at 12:50

3 Answers3

2

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
PaulS
  • 21,159
  • 2
  • 9
  • 26
1
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.

Julian
  • 6,586
  • 2
  • 9
  • 33
  • Thanks a lot for this! It says extract numeric is outdated though? – github292929 May 02 '22 at 12:32
  • Yes, this one should not be used. From the help file: "DEPRECATED: please use readr::parse_number() instead." –  May 02 '22 at 12:34
  • @Adam I then get: Error in parse_vector(x, col_number(), na = na, locale = locale, trim_ws = trim_ws) : argument "x" is missing, with no default – github292929 May 02 '22 at 12:40
  • @github292929 I would guess then that either (a) your packages may need updating or (b) your real problem has features outside of your reproducible example. Because it does work. –  May 02 '22 at 12:44
1

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