How to detect positions of a character in string using dplyr

Viewed 111

I have the following data frame:

library(tidyverse)
df <- tribble(
       ~sname, ~seq,
       "foo", "TTAW",
       "bar", "ACTN",
       "qux", "AAAA"
      )
 
df

What I want is to have 3rd column that locate the positions of "T" in every row. The end result looks like this:

  sname seq  t_pos
  foo   TTAW 1,2
  bar   ACTN 3
  qux   AAAA 0

How can I achieve that? I tried this but doesn't work:

df %>% 
  dplyr::mutate(t_pos = paste0( list(which(strsplit(seq, "")[[1]] == "T") ) ))

What's the right way to do it?

1 Answers

You can add rowwise to your attempt :

library(dplyr)

df %>% 
  rowwise() %>%
  mutate(t_pos = toString(which(strsplit(seq, "")[[1]] == "T")))

#  sname seq   t_pos 
#  <chr> <chr> <chr> 
#1 foo   TTAW  "1, 2"
#2 bar   ACTN  "3"   
#3 qux   AAAA  ""    

With map_chr :

df %>% 
  mutate(t_pos = purrr::map_chr(strsplit(seq, ""), ~toString(which(.x == "T"))))

and in base R :

df$t_pos <- sapply(strsplit(df$seq, ''), function(x) toString(which(x == 'T')))
Related