如何创建仅包含列表中唯一元素的表格,以便按频率对元素进行排序?

时间:2014-11-06 13:41:46

标签: r

我已经尝试过运行下面的代码,但它不起作用,因为参数的长度不一样。

sentence= "I like tea and I love coffee and biscuits"
    words = function(x) {
      txt = unlist(strsplit(x,' '))
      wl = list()
      for(i in seq_along(txt)) {
        wrd = txt[i]
        wl[[wrd]] = c(wl[[wrd]], i)
      }
      class(wl) <- "wordclass"
      return(wl)
    }
    summary.wordclass <- function(y) {
      cat("the frequency of words",names(sort(table(y), decreasing=TRUE)),"\n")
    }
    wordfreq=words(sentence)
    summary(wordfreq)

我希望得到像

这样的输出
[1] "I"     "and"   "like"    "tea"   "love"   "coffee" 

但是,我收到了错误

  

表(y)中的错误:所有参数必须具有相同的长度

如果有人能提供帮助那就太棒了!

1 个答案:

答案 0 :(得分:0)

names(sort(table(unlist(strsplit(sentence," "))),decreasing=T))

为你工作?

输出

[1] "and" "I" "biscuits" "coffee" "like" "love" "tea"