Guest User

Untitled

a guest
Jun 29th, 2017
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.54 KB | None | 0 0
  1. ## R Code
  2. library(data.table)
  3. library(pipeR)
  4. library(tidyr)
  5.  
  6. tt = c("BAGFFABFC",
  7.        "BAGFFABFC",
  8.        "xxxFAABCCGBBF",
  9.        "xxxFAABFCGFBF",
  10.        "xxxxGBBFCGFEEBA",
  11.        "xxxxGBBFGGFEEBA",
  12.        "xxxxxxxxxxxxEEBACAEEGFGAA",
  13.        "xxxxxxxxxxxxxxxxxxGFGFAACDABG",
  14.        "xxxxxxxxxxxxxxxxxxGFGFACCDABG")
  15.  
  16. s1 = sapply(tt,function(x){
  17.  
  18.   charlen = nchar(x)
  19.   list(
  20.     len = rep(charlen,7), ## 字串長度
  21.     global_charnum = seq(charlen-6,charlen,1), ## 字母在 1 ~ 29 哪個位置
  22.     local_charnum = seq(-7,-1,1),              ## 字母在 -1 ~ -7 哪個位置
  23.     stri = unlist(strsplit(gsub("(.{1})","\\1 ",substr(x,charlen - 6, charlen)),split=" ")) ## 將後7個字母切開
  24.    
  25.   )
  26.  
  27. },USE.NAMES = F) %>>% (apply(X=.,MARGIN=1,function(x) do.call(cbind,x))) %>>% data.table %>>%  ## 組成字母在哪個位置的資料格式 (data.table)
  28.   `[`(,c("stri","local_charnum","numer") := list(factor(stri),factor(local_charnum),1)) %>>% ## numer 為分子 初始為 1
  29.   unique ## distinct 相同字串長度、字母、位置
  30.  
  31. s2 = s1 %>>% `[`(,.N,by=c("global_charnum","stri"))
  32.  
  33. s3 = merge(s1,s2,by=c("global_charnum","stri"),all.x=T)  %>>% ## By glocbal_charnum, stri 作 left join
  34.   `[`(,.(len,global_charnum,local_charnum,stri,val = numer/N)) %>>% ## val = numer/N 為矩陣內的值
  35.   (split(x=.,f=.$len)) %>>%  ## By 字串長度切割成 list 格式
  36.   (lapply(X=.,FUN = function(x){  
  37.     x %>>% `[`(,.(local_charnum,stri,val)) %>>% (spread(data=.,local_charnum,val,drop=F,fill=0)) ## long 轉 wide 格式
  38.     }))
Advertisement
Add Comment
Please, Sign In to add comment