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

Extracting a letter and put it in a separated column in R

I have data set like this:

df<-data.frame(ID=(1:5), cloumn1=c("AA","GG","AG","AA","AT"), cloumn2=c("AA","GG","AG","AA","AT"), stringsAsFactors=FALSE)
df
ID cloumn1 cloumn2
 1      AA      AA
 2      GG      GG
 3      AG      AG
 4      AA      AA
 5      AT      AT

I want to separate each column into 2 letters so the output will look something like this:

ID cloumn1.A cloumn1.B cloumn2.A cloumn2.B
 1         A         A         A         A
 2         G         G         G         G
 3         A         G         A         G
 4         A         A         A         A
 5         A         T         A         T

Can you help me please?

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

>Solution :

library(tidyverse)

df %>% 
  pivot_longer(-ID) %>% 
  mutate(tmp = str_split(value, pattern = "")) %>% 
  unnest(tmp) %>% 
  group_by(ID, name) %>% 
  mutate(id_row = LETTERS[row_number()]) %>% 
  pivot_wider(id_cols = c(ID, name), names_from =c(name, id_row), values_from = tmp, names_sep = ".") %>% 
  ungroup()

#> # A tibble: 5 x 5
#>      ID cloumn1.A cloumn1.B cloumn2.A cloumn2.B
#>   <int> <chr>     <chr>     <chr>     <chr>    
#> 1     1 A         A         A         A        
#> 2     2 G         G         G         G        
#> 3     3 A         G         A         G        
#> 4     4 A         A         A         A        
#> 5     5 A         T         A         T

data

df <-
  data.frame(
    ID = (1:5),
    cloumn1 = c("AA", "GG", "AG", "AA", "AT"),
    cloumn2 = c("AA", "GG", "AG", "AA", "AT"),
    stringsAsFactors = FALSE
  )

Created on 2021-11-05 by the reprex package (v2.0.1)

data.table

library(data.table)

setDT(df)

melt(data = df, id.vars = "ID") %>% 
  .[, list(value = unlist(strsplit(value, split = ""))), by = list(ID, variable)] %>% 
  .[, id_row := LETTERS[rowid(ID, variable)]] %>% 
  dcast(formula = ID ~ variable + id_row, value.var = "value")

   ID cloumn1_A cloumn1_B cloumn2_A cloumn2_B
1:  1         A         A         A         A
2:  2         G         G         G         G
3:  3         A         G         A         G
4:  4         A         A         A         A
5:  5         A         T         A         T
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