我和我的团队正在处理数千个具有相似段的 URL。
有些 URL 在我们感兴趣的位置有一个段(“seg”,复数,“segs”)。其他类似的 URL 在我们感兴趣的位置上有不同的段。
我们需要对由 URL 和关联的唯一段组成的数据框进行排序
在感兴趣的位置,显示这些独特段的频率。
这是一个简化的示例:
url <- c(1, 3, 1, 4, 2, 3, 1, 3, 3, 3, 3, 2)
seg <- c("a", "c", "a", "d", "b", "c", "a", "x", "x", "y", "c", "b")
df <- data.frame(url,seg)
我们正在寻找以下内容:
url freq seg
1 3 a in other words, url #1 appears three times each with a seg = "a",
2 2 b in other words: url #2 appears twice each with a seg = "b",
3 3 c in other words: url #3 appears three times with a seg = "c",
3 2 x two times with a seg = "x", and,
3 1 y once with a seg = "y"
4 1 d etc.
我可以使用循环和几个小步骤到达那里,但我相信有一种更优雅的方法可以做到这一点。这是我的不优雅的方法:
创建具有 num.unique 行和三列(url、freq、seg)的空数据框
result <- data.frame(url=0, Freq=0, seg=0)
确定唯一的 URL
unique.df.url <- unique(df$url)
循环遍历数据框
for (xx in unique.df.url) {
url.seg <- df[which(df$url == unique.df.url[xx]), ] # create a dataframe for each of the unique urls and associated segs
freq.df.url <- data.frame(table(url.seg)) # summarize the frequency distribution of the segs by url
result <- rbind(result,freq.df.url) # append a new data.frame onto the last one
}
消除数据框中频率 = 0 的行
result.freq <- result[which(result$Freq |0), ]
按 URL 对数据框排序
result.order <- result.freq[order(result.freq$url), ]
这产生了预期的结果,但由于它是如此不优雅,我担心一旦我们扩大规模,所需的时间将是令人望而却步的,或者至少是一个令人担忧的问题。有什么建议么?