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

后端 未结 3 970
萌比男神i
萌比男神i 2020-12-07 13:19

I know I\'ve come across this problem before, but I\'m having a bit of a mental block at the moment. and as I can\'t find it on SO, I\'ll post it here so I can find it next

相关标签:
3条回答
  • 2020-12-07 13:41

    First of all: if you use str(df) you'll see that df$pre is list. I think you want vector (but I might be wrong).
    Return to problem - in this case I will use gsub:

    df$pre <- gsub("[0-9]", "", df$lab)
    df$suf <- gsub("[A-Z]", "", df$lab)
    

    This guarantee that both columns are vectors, but it fail if your label is not from key (i.e. 'AB01B').

    0 讨论(0)
  • 2020-12-07 13:48

    with purrr::map this would be

    df$suf %>%  map_chr(c(2)) 
    

    for further info on purrr::map

    0 讨论(0)
  • 2020-12-07 13:52

    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)
    
    0 讨论(0)
提交回复
热议问题