R:通过标签组合不同长度的频率列表?
我是R的新手,但我真的很喜欢它,并希望不断提高。现在,在寻找了一段时间后,我需要你帮忙 这是给定的情况: 1) 我有句子(句子1和句子2-所有单词都是小写),并创建单词的排序频率列表:R:通过标签组合不同长度的频率列表?,r,list,frequency,words,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
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)
现在,请问,我如何将这两个频率列表结合起来,我将有以下内容:
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”和“虽然”之间添加带有“and”标签的列
我只想在新行中添加新句子,并将所有尚未在列表列中的not单词(此处,“and”将位于“you”的右侧),然后再次对列表进行排序。但是,我还没有做到这一点,因为根据现有标签对新句子的单词频率进行排序已经不起作用了(当再次出现例如“car”时,新句子的car频率应该写入新句子的行和列“car”,但当出现例如“you”时这是第一次,它的频率应该写在新句子的行和一个新的列中,标记为“you”)。这并不是您所描述的,但您的目标对我来说更合理,它是按行组织的,而不是按列组织的(而且R处理以这种方式组织的数据更容易一些)
#将表格转换为数据帧
乔兰,你救了我一天!这就是我所需要的,它看起来很完美。非常感谢。
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
#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