如何在r中找到标签或单词的频率

时间:2018-03-02 12:07:16

标签: r

我正在处理堆栈溢出数据转储.csv文件,我需要找到:

数据集中前8个最常用的标记。 为此,我看到与 data1.PostTypeId 列中每行相关联的标记集。标记的频率等于具有该标记的问题数tag。(表示标签的频率等于具有该标签的行数)

注1:文件太大,有超过100万行

注2:我是R的初学者,所以我需要最简单的方法。我的尝试是使用表函数,但我得到的是标签列表,我无法找出顶部的

这是我使用的表格的示例如下:

例如,假设“java”频率最高(因为它出现在所有行中最多)

然后标签“python-3.x”是第二高的频率(因为在所有行中出现最多) 所以基本上我需要回顾表格中的第二列,那里有前8位

等等......

enter image description here

2 个答案:

答案 0 :(得分:1)

如果我理解正确,这应该可以解决你的问题

library(stringr)
library(data.table)

# some dummy data
dat = data.table(id = 1:3, tags = c("<java><android><selenium>",
                                    "<java><javafx>",
                                    "<apache><android>"))

tags = apply(str_split(dat$tags, pattern = "><", simplify = T),
             2, function(x) str_replace(x, "<|>", "")) # separate one tag in each column

foo = cbind(dat[, .(id)], tags) # add the separated tags to the data
foo[foo==""] = NA # substitute empty strings with NA
foo = melt.data.table(foo, id.vars = "id") # transform to long format
foo = foo[, .N, by = value] # calculate frequency
foo[, .SD[N %in% head(N, n = 1)]] # change the value of "n" to the number you want

     value N
1:    java 2
2: android 2
3:      NA 2

答案 1 :(得分:1)

使用带有(可选)magrittr管道的基础R以提高可读性:

library(magrittr)
# Make a vector of all the tags present in data
tags_sep <- tags %>%
  strsplit("><") %>%
  unlist()
# Clean out the remaining < and >
tags_sep <- gsub("<|>", "", tags_sep)
# Frequency table sorted
tags_table <- tags_sep %>%
  table %>%
  sort(decreasing = TRUE)
# Print the top 10 tags
tags_table[1:10]

      java             android          amazon-ec2 amazon-web-services android-mediaplayer 
          4                   2                   1                   1                   1 
      antlr              antlr4        apache-kafka              appium             asp.net 
          1                   1                   1                   1                   1 

数据

tags <- c(
  "<java><android><selenium><appium>",
  "<java><javafx><javafx-2>",
  "<apache-kafka>",
  "<java><spring><eclipse><gradle><spring-boot>",
  "<c><stm32><led>",
  "<asp.net>",
  "<python-3.x><python-2.x>",
  "<http><server><Iocalhost><ngrok>",
  "<java><android><audio><android-mediaplayer>",
  "<antlr><antlr4>",
  "<ios><firebase><swift3><push-notification>",
  "<amazon-web-services><amazon-ec2><terraform>",
  "<xamarin.forms>",
  "<gnuplot>",
  "<rx-java><rx-android><rx-binding>",
  "<vim><vim-plugin><syntastic>",
  "<plot><quantile>",
  "<node.js><express-handlebars>",
  "<php><html>"
)