在 R 中生成 table 个唯一子字符串

Generating a table of unique substrings in R

所以我有一个非常大的数据集,我想知道具有大约 400,000 个观察值的列的唯一值,每个观察值如下所示: identifier:abzcd:def:RANDOMNUMBERSTRINGidentifier:de:ghijklm:RANDOMNUMBERSTRING。 我只希望随机数字符串之前的部分具有唯一匹配项。换句话说,我只想过滤掉代码的重复项:identifier:LETTERS:LETTERS unique 函数不起作用,看起来我需要确切地知道我想过滤哪些子字符串或子字符串要使用多长时间才能使用 substr 函数。关于如何执行此操作有什么建议吗?

以下是一些可以作为模型的数据:

randz <- data.frame(id =
                      sprintf("identifier:%s%s%s:%s%s%s:%s",
                 sample(letters, 1000,replace = T ),
                 sample(letters, 1000,replace = T ),
                 sample(letters, 1000,replace = T ),
                 sample(letters, 1000,replace = T ),
                 sample(letters, 1000,replace = T ),
                 sample(letters, 1000,replace = T ),
                 sample(6000:7000, 1000, replace = T )))
randz

这是使用 tidyverse

的一种简单方法
# Fake Data
randz <- data.frame(id =
                      sprintf("identifier:%s%s%s:%s%s%s:%s",
                 sample(letters, 1000,replace = T ),
                 sample(letters, 1000,replace = T ),
                 sample(letters, 1000,replace = T ),
                 sample(letters, 1000,replace = T ),
                 sample(letters, 1000,replace = T ),
                 sample(letters, 1000,replace = T ),
                 sample(6000:7000, 1000, replace = T )))

这里我会用str_remove函数去掉最后一个冒号(:)后面的数字(\d+),用“$”表示字符串的结尾。计数也将提取每个唯一值,列 "n" 将指示它出现的次数。


# Libraries
library(tidyverse)
randz %>% 
  mutate(out = str_remove(string = id,
                           pattern = ":\d+$")) %>% 
  count(out,sort = TRUE)

输出:

A tibble: 1,000 x 2
   out                    n
   <chr>              <int>
 1 identifier:aar:muk     1
 2 identifier:abe:tlo     1
 3 identifier:abg:qux     1
 4 identifier:abh:bxx     1
 5 identifier:abl:vdj     1

您可以使用正则表达式提取它们。这是使用 stringr 包的示例。

str_extract("identifier:de:ghijklm:RANDOMNUMBERSTRING", "(identifier\:[a-z]+\:[a-z]+)")