2017-10-17 111 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