2017-10-17 62 views
1

我想找到的每個字符串中的captial字母和計數多少每串 在那裏例如找到captial字母串在

t = c("gctaggggggatggttactactGtgctatggactac", "gGaagggacggttactaCgTtatggactacT", "gcGaggggattggcttacG") 

ldply(str_match_all(t,"[A-Z]"),length) 

應用上述功能時,我的輸出

1 4 2 

但我的願望輸出是

[1; G -1

[2; G -1 C -1 Ť-2

[3; G -2

回答

2

如果擴展docendo的回答是你的確切要求的格式

lapply(stringr::str_extract_all(t, "[A-Z]"), 
     function(x) { 
     x = table(x) 
     paste(names(x), x, sep = "-") 
     }) 

# [[1]] 
# [1] "G-1" 
# 
# [[2]] 
# [1] "C-1" "G-1" "T-2" 
# 
# [[3]] 
# [1] "G-2" 

以及我如何做tidyverse

library(tidyverse) 
data = data.frame(strings = c("gctaggggggatggttactactGtgctatggactac", "gGaagggacggttactaCgTtatggactacT", "gcGaggggattggcttacG")) 
data %>% 
    mutate(caps_freq = stringr::str_extract_all(strings, "[A-Z]"), 
     caps_freq = map(caps_freq, function(letter) data.frame(table(letter)))) %>% 
    unnest() 
#        strings letters Freq 
# 1 gctaggggggatggttactactGtgctatggactac  G 1 
# 2  gGaagggacggttactaCgTtatggactacT  C 1 
# 3  gGaagggacggttactaCgTtatggactacT  G 1 
# 4  gGaagggacggttactaCgTtatggactacT  T 2 
# 5     gcGaggggattggcttacG  G 2 
+0

與@ docendo的答案有什麼不同?我沒有看到它(除了在末尾做「粘貼」) - 相同的答案imo – Sotos

+0

因爲這是請求的輸出。正如我很清楚地說的,我延長了他的答案...... – zacdav

+0

正確的做法是在他的回答下評論,可以添加一個額外的步驟來適應粘貼部分。重新發布相同的答案只是添加一行代碼聽起來有點像剽竊。然而,'tidyverse'加成使得它可以作爲一個新的答案(我也喜歡它的輸出更好說實話) – Sotos

5

可以提取所有大寫字母,然後用表計算頻率:

library(stringr) 
lapply(str_extract_all(t, "[A-Z]"), table) 
# [[1]] 
# 
# G 
# 1 
# 
# [[2]] 
# 
# C G T 
# 1 1 2 
# 
# [[3]] 
# 
# G 
# 2