【问题标题】:Subset data frame by row according to length of ngrams根据 ngram 的长度逐行子集数据
【发布时间】:2017-03-22 09:46:06
【问题描述】:

我有一个数据框,其中包含许多术语(不同大小的 ngram,最多 5 克)及其各自的频率:

df = data.frame(term = c("a", "a a", "a a card", "a a card base", "a a card base ne",
                         "a a divorce", "a a divorce lawyer", "be", "be the", "be the one"), 
                freq = c(131, 13, 3, 2, 1, 1, 1, 72, 17, 5))

这给了我们:

                 term freq
1                   a  131
2                 a a   13
3            a a card    3
4       a a card base    2
5    a a card base ne    1
6         a a divorce    1
7  a a divorce lawyer    1
8                  be   72
9              be the   17
10         be the one    5

我想要的是把 unigrams(只有一个词的词条)、bigrams(只有两个词的词条)、trigrams、fourgrams 和 Fivegrams 分成不同的数据框:

例如,仅包含一元组的“df1”如下所示:

                 term freq
1                   a  131
2                  be   72

“df2”(二元组):

                 term freq
1                 a a   13
2              be the   17

“df3”(三元组):

                 term freq
1            a a card    3
2         a a divorce    1
3          be the one    5

等等。任何的想法?可能是正则表达式?

【问题讨论】:

    标签: r dataframe split


    【解决方案1】:

    您可以按空间计数进行拆分,即

    split(df, stringr::str_count(df$term, '\\s+'))
    
    #$`0`
    #  term freq
    #1    a  131
    #8   be   72
    
    #$`1`
    #    term freq
    #2    a a   13
    #9 be the   17
    
    #$`2`
    #          term freq
    #3     a a card    3
    #6  a a divorce    1
    #10  be the one    5
    
    #$`3`
    #                term freq
    #4      a a card base    2
    #7 a a divorce lawyer    1
    
    #$`4`
    #              term freq
    #5 a a card base ne    1
    

    一个完全基于 R 的解决方案(正如@akrun 提到的那样)是,

    split(df, lengths(gregexpr("\\S+", df$term)))
    

    【讨论】:

    • 此外,它还返回一个包含五个元素(unigrams、bigrams、....、最多为五元组)的列表。这正是我想要的。非常感谢。
    • 这是另一个base R,即split(df, lengths(gregexpr("\\S+", df$term)))
    猜你喜欢
    • 2020-02-04
    • 1970-01-01
    • 2014-08-03
    • 2021-12-19
    • 2013-02-25
    • 1970-01-01
    • 1970-01-01
    • 2014-09-21
    • 1970-01-01
    相关资源
    最近更新 更多