[英]R: combining frequency lists with different lengths by labels?
我是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”之间添加标签“和”的列。
我想到只是将新句子添加到一个新行中,并将所有尚未列入列表中的单词放在列中(此处,“和”将位于“you”的右侧)并再次对列表进行排序。 但是,我没有管理这个,因为已经根据现有标签对新句子的词语频率进行排序尚未起作用(当有例如“汽车”时,新句子的汽车频率应写入新句子的行和“car”的列,但是当第一次有例如“你”时,它的频率应写入新句子的行和标有“你”的新列。
这不完全是你所描述的,但是你的目标对我来说更有意义的是按行而不是按列组织(并且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.y
参数,而不是仅仅by
在merge
可以指示特定的列合并。如果名字都没有在每个数据帧中的相同。 此外, merge
的suffix
参数将控制count列的唯一名称。 默认是附加.x
和.y
但您可以更改它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.