Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to subset character string for each list in R?

How to subset character string for each list in R?

Here is dummy dataset

mylist <- list(c("atgtgt"), c("cgcgatat"), c("cgccccc"))
mylist
# [[1]]
# [1] "atgtgt"
# 
# [[2]]
# [1] "cgcgatat"
# 
# [[3]]
# [1] "cgccccc"

And I would like that subset first 3 characters from each lists.
Expected Output is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# [[1]]
# [1] "atg"
# 
# [[2]]
# [1] "cgc"
# 
# [[3]]
# [1] "cgc"

>Solution :

We can do it in base R with applying substring() to all elements of mylist

lapply(mylist, function(x) substring(x, 1, 3))

A tidyverse approach:

library(stringr)
library(purrr)

mylist_sub <- map(mylist, ~ str_sub(.x, start = 1, end = 3))
[[1]]
[1] "atg"

[[2]]
[1] "cgc"

[[3]]
[1] "cgc"

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading