简体   繁体   中英

Reduce and split into several column in R

I have one problem with my Amino_acid mutation data. for example,

p.K303R   
p.?
p.R1450*

and I want like this outopt

AA_mutation wt_residue  position    mt_residue
p.K303R       K          303           R
p.?         
p.R1450*      R           1450         *

I want to remove "p.","?" from the data and also split into three new variable. I have managed it on excel but not in R platform. Could someone help me please on R. Kind regards Fakhrul

Using dplyr and extract (have some reading here ), we can use:

library(dplyr)
df <- data.frame(AA_mutation = c("p.K303R", "p.?", "p.R1450*"))
df <- df %>%
  extract(AA_mutation, 
          into = c("wt_residue", "position", "mt_residue"), 
          regex = "p\\.([A-Z])?(\\d+)?([A-Z*])?",
          remove = FALSE)
df

Yielding

  AA_mutation wt_residue position mt_residue
1     p.K303R          K      303          R
2         p.?       <NA>     <NA>       <NA>
3    p.R1450*          R     1450          *

Here is an option with base R

lst <- regmatches(df1[[1]], gregexpr("([a-z]+)|([A-Z*]+)|[0-9]+", df1[[1]], perl = TRUE))
res <- do.call(rbind.data.frame, lapply(lst, `length<-`, max(lengths(lst))))
names(res) <- c("AA_mutation", "wt_residue",  "position",    "mt_residue")
res
#  AA_mutation wt_residue position mt_residue
#1           p          K      303          R
#2           p       <NA>     <NA>       <NA>
#3           p          R     1450          *

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM