3

我有一长串重复的字符串——这里有一些玩具数据,

unique_items <- c('shoes', 'shirt', 'pants', 'socks')
l <- unique_items[sample(1:4, 100000, replace = TRUE)]

我现在想在 unique_items 中找到每个项目的所有索引。

一个天真的解决方案是:

item_indices <- vector(mode = 'list', length = length(unique_items))
names(item_indices) <- unique_items
for (idx in 1:length(unique_items))
{
  item <- unique_items[idx]
  item_indices[[item]] <- which(l == item)
}

但是,当我有一个巨大的列表时,这非常慢。

有没有更快的方法来做到这一点?

4

1 回答 1

6
item_indices <- split(seq_along(l), l)
于 2013-08-12T21:18:01.067 回答