Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## R Code
- library(data.table)
- library(pipeR)
- library(tidyr)
- tt = c("BAGFFABFC",
- "BAGFFABFC",
- "xxxFAABCCGBBF",
- "xxxFAABFCGFBF",
- "xxxxGBBFCGFEEBA",
- "xxxxGBBFGGFEEBA",
- "xxxxxxxxxxxxEEBACAEEGFGAA",
- "xxxxxxxxxxxxxxxxxxGFGFAACDABG",
- "xxxxxxxxxxxxxxxxxxGFGFACCDABG")
- s1 = sapply(tt,function(x){
- charlen = nchar(x)
- list(
- len = rep(charlen,7), ## 字串長度
- global_charnum = seq(charlen-6,charlen,1), ## 字母在 1 ~ 29 哪個位置
- local_charnum = seq(-7,-1,1), ## 字母在 -1 ~ -7 哪個位置
- stri = unlist(strsplit(gsub("(.{1})","\\1 ",substr(x,charlen - 6, charlen)),split=" ")) ## 將後7個字母切開
- )
- },USE.NAMES = F) %>>% (apply(X=.,MARGIN=1,function(x) do.call(cbind,x))) %>>% data.table %>>% ## 組成字母在哪個位置的資料格式 (data.table)
- `[`(,c("stri","local_charnum","numer") := list(factor(stri),factor(local_charnum),1)) %>>% ## numer 為分子 初始為 1
- unique ## distinct 相同字串長度、字母、位置
- s2 = s1 %>>% `[`(,.N,by=c("global_charnum","stri"))
- s3 = merge(s1,s2,by=c("global_charnum","stri"),all.x=T) %>>% ## By glocbal_charnum, stri 作 left join
- `[`(,.(len,global_charnum,local_charnum,stri,val = numer/N)) %>>% ## val = numer/N 為矩陣內的值
- (split(x=.,f=.$len)) %>>% ## By 字串長度切割成 list 格式
- (lapply(X=.,FUN = function(x){
- x %>>% `[`(,.(local_charnum,stri,val)) %>>% (spread(data=.,local_charnum,val,drop=F,fill=0)) ## long 轉 wide 格式
- }))
Advertisement
Add Comment
Please, Sign In to add comment