R:通过标签组合不同长度的频率列表?

时间:2012-01-12 09:18:22

标签: r list frequency words

我是R的新手,但是非常喜欢它,并希望不断改进。现在,经过一段时间的搜索,我需要求你帮忙。

这是给定的案例:

1)我有句子(句子1和句子2 - 所有单词都已经小写)并创建他们单词的排序频率列表:

sentence.1 <- "bob buys this car, although his old car is still fine." # saves the sentence into sentence.1
sentence.2 <- "a car can cost you very much per month."

sentence.1.list <- strsplit(sentence.1, "\\W+", perl=T) #(I have these following commands thanks to Stefan Gries) we split the sentence at non-word characters
sentence.2.list <- strsplit(sentence.2, "\\W+", perl=T)

sentence.1.vector <- unlist(sentence.1.list) # then we create a vector of the list
sentence.2.vector <- unlist(sentence.2.list) # vectorizes the list

sentence.1.freq <- table(sentence.1.vector) # and finally create the frequency lists for 
sentence.2.freq <- table(sentence.2.vector)

结果如下:

sentence.1.freq:
although      bob     buys      car     fine      his       is      old    still     this 
       1        1        1        2        1        1        1        1        1        1

sentence.2.freq:
a   can   car  cost month  much   per  very   you 
1     1     1     1     1     1     1     1     1 

现在,请问,如何将这两个频率列表组合起来,我将会有以下内容:

 a  although  bob  buys  can  car  cost fine his  is  month much old per still this very you
NA         1    1     1   NA    2    NA    1   1   1     NA   NA   1  NA     1    1   NA  NA
 1        NA   NA    NA    1    1     1   NA  NA  NA      1    1  NA   1    NA   NA    1   1

因此,这个“表格”应该是“灵活的”,以便在输入带有该词的新句子的情况下,例如“和”,表格将在“a”和“though”之间添加标签“and”的列。

我想到只是将一个新句子添加到一个新行中并将所有尚未列入列表的单词放在列中(此处,“和”将位于“you”的右侧)并再次对列表进行排序。但是,我没有管理这个,因为已经根据现有标签对新句子的词语频率进行排序尚未起作用(当有例如“汽车”时,新句子的汽车频率应写入新句子的行和“car”的列,但是当第一次有例如“你”时,它的频率应该被写入新句子的行和一个标有“你”的新列。

1 个答案:

答案 0 :(得分:3)

这不是完全你描述的内容,但是你的目标对我来说更有意义的是按行而不是按列组织(并且R处理数据以这种方式组织更多一点很容易。)

#Convert tables to data frames
a1 <- as.data.frame(sentence.1.freq)
a2 <- as.data.frame(sentence.2.freq)

#There are other options here, see note below
colnames(a1) <- colnames(a2) <- c('word','freq')
#Then merge
merge(a1,a2,by = "word",all = TRUE)
       word freq.x freq.y
1  although      1     NA
2       bob      1     NA
3      buys      1     NA
4       car      2      1
5      fine      1     NA
6       his      1     NA
7        is      1     NA
8       old      1     NA
9     still      1     NA
10     this      1     NA
11        a     NA      1
12      can     NA      1
13     cost     NA      1
14    month     NA      1
15     much     NA      1
16      per     NA      1
17     very     NA      1
18      you     NA      1

然后,您可以继续使用merge添加更多句子。为简单起见,我转换了列名,但还有其他选项。在by.x中使用by.yby参数而不仅仅是merge可以指示如果每个数据框中的名称不相同,则合并特定列。此外,suffix中的merge参数将控制计数列的唯一名称。默认设置是附加.x.y,但您可以更改它。