How to subset character string for each list in R?

Advertisements

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:

# [[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"

Leave a ReplyCancel reply