我是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
因此,这个"表"应该是"灵活的",这样,如果输入一个带有单词的新句子,例如"and",该表将在"a"one_answers"尽管"之间添加带有标签"and"的列。
我想把新的句子添加到新行中,把所有还没有在列表中的单词(这里,"and"在"you"的右边)放在一列,然后再次对列表进行排序。然而我还没有做到这一点,因为根据现有标签对新句子的单词频率进行排序已经不起作用了(当再次出现例如"car"时,新句子的car频率应该写在新句子的行和列中,但当出现例如"you"时第一次,它的频率应该写在新句子的行和一个新的列中,标记为"你")。
这并不是你所描述的,但你的目标对我来说更有意义,因为它是按行而不是按列组织的(而且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
来添加更多的句子。为了简单起见,我转换了列名,但还有其他选项。如果每个数据帧中的名称不相同,则在merge
中使用by.x
和by.y
参数而不是仅使用by
可以指示合并的特定列。此外,merge
中的suffix
参数将控制如何为计数列指定唯一名称。默认情况是附加.x
和.y
,但您可以更改。