3

我想生成一个向量,其中包含向量中存在的字母表中所有 26 个数字的总数a

a <- c("aabead", "dadfhhsa")

例如,这个向量中的 a 等于 5,b 等于 1,d 等于 2,z 等于 0,x 等于 0,等等。

4

2 回答 2

10

您只需要函数tablestrsplit,并获得以下帮助unlist

table(unlist(strsplit(a, ""), use.names=FALSE))
#
# a b d e f h s 
# 5 1 3 1 1 2 1
  • strsplit将字符串“分解”成单个字母。它为向量“a”中的每个字符串创建一个list, 一个项目。
  • 由于 的输出strsplit是 a list,因此您需要unlist先将其制成表格。use.names = FALSE只是提供了unlist速度提升。
  • table,正如您现在可能已经猜到的那样,将输出制成表格。

如果你真的想要零值,你也需要factor在里面加上一个内置letters常量的帮助:

table(factor(unlist(strsplit(a, ""), use.names=FALSE), levels=letters))
#
# a b c d e f g h i j k l m n o p q r s t u v w x y z 
# 5 1 0 3 1 1 0 2 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 

更新

在处理这些类型的问题时,您必须遍历大量值,重要的是要考虑如何处理问题。

例如,在接受的答案中,unlist(strsplit(...))被调用了 26 次:每个字母一次。通过首先拆分和取消列出值,然后使用sapply. 比较以下的性能fun1a差异fun2a

作为参考,我还对factor基于我的解决方案以及使用tabulate. 可以看出,这些比使用 循环遍历单个字母要快得多sapply

library(stringi)
set.seed(1)
n <- 100000
a <- stri_rand_strings(n, sample(10, n, TRUE), "[a-z]")

fun1a <- function() sapply(letters, function(x) x<-sum(x==unlist(strsplit(a,""))))
fun1b <- function() {
  temp <- unlist(strsplit(a, ""))
  sapply(letters, function(x) {
    sum(x == temp)
  })
}
fun2 <- function() table(factor(unlist(strsplit(a, "", TRUE), use.names=FALSE), levels=letters))
fun3 <- function() {
  `names<-`(tabulate(
    factor(unlist(strsplit(a, "", TRUE), use.names = FALSE), 
           letters), nbins = 26), letters)
}

library(microbenchmark)
microbenchmark(fun1a(), fun1b(), fun2(), fun3(), times = 10)
# Unit: milliseconds
#     expr        min         lq       mean     median         uq        max neval
#  fun1a() 1025.45449 1177.90226 1189.49551 1190.11137 1238.66071 1352.05645    10
#  fun1b()  102.94881  114.08700  115.14852  115.87184  119.06776  124.64735    10
#   fun2()   53.46341   58.67832   67.50402   68.94933   70.71005   95.10771    10
#   fun3()   46.65357   49.79365   51.68536   51.55922   54.36390   57.07582    10
于 2013-10-20T10:32:57.727 回答
6

letters您可以使用R 内置向量以这种方式进行操作

 > sapply(letters, function(x) x<-sum(x==unlist(strsplit(a,""))))
a b c d e f g h i j k l m n o p q r s t u v w x y z 
5 1 0 3 1 1 0 2 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
于 2013-10-20T10:42:44.100 回答