4

我是 R 的新手,但真的很喜欢它并希望不断改进。现在,经过一段时间的搜索,我需要向您寻求帮助。

这是给定的情况:

1)我有句子(sentence.1 和 sentence.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

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

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

4

1 回答 1

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.xandby.y参数而不是byinmerge可以指示特定列合并。此外,suffix参数 inmerge将控制如何为计数列赋予唯一名称。默认为追加.x.y但您可以更改它。

于 2012-01-12T17:49:29.340 回答