【问题标题】:R Programming- sort a list by number of wordsR Programming-按字数对列表进行排序
【发布时间】:2016-09-20 14:34:25
【问题描述】:

我有一个列表,其中包含对一项调查的多个回复。我正在尝试按每个响应中的字数对列表中的元素进行排序。我在网上找到的所有内容都使用 nchar,它按字符数而不是单词数排序。

这是我目前所拥有的:

gala.vector <- unlist(strsplit, gala.list, " ")

用空格分割向量以在单词之间分割

gala.list.sorted <- gala.list[order(gala.vector, decreasing=TRUE)]

但是我被告知参数“gala.vector 不是向量并收到错误消息

【问题讨论】:

    标签: r sorting vector


    【解决方案1】:

    可重现的示例和函数解决方案:

    w <- c("this has four words", 
      "this one has five words", 
      "two words")
    
    word_count <- function(x) {
      x <- lapply(x, function(y) trimws(strsplit(y, " ")[[1]]))
      x <- lapply(x, function(y) y[y != ""])
      unlist(lapply(x, length))
    }
    
    > word_count(w)
    # [1] 4 5 2 
    
    sort_by_wc <- function(x, decreasing = TRUE) {
      seq <- word_count(x)
      x[order(seq, decreasing = decreasing)]
    }
    
    > sort_by_wc(w)
    # [1] "this one has five words" 
    # [2] "this has four words"    
    # [3] "two words" 
    

    【讨论】:

      【解决方案2】:

      我们可以split每个list元素('gala.list'),unlist它('lst1')中的句子,使用lengths得到每个'长度' list 元素和order 用于订购'gala.list'

      lst1 <- lapply(gala.list, function(x) unlist(strsplit(x, " ")))
      gala.list[order(lengths(lst1), decreasing = TRUE)]      
      

      数据

      gala.list <- list("something else to do", "three words only",    
                    "using dput")                     
      

      【讨论】:

        猜你喜欢
        • 2014-08-31
        • 1970-01-01
        • 1970-01-01
        • 2012-12-04
        • 2019-02-13
        • 1970-01-01
        • 2012-04-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多