[英]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.