gpt4 book ai didi

R:按标签组合不同长度的频率列表?

转载 作者:行者123 更新时间:2023-12-04 12:37:23 24 4
gpt4 key购买 nike

我是 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”的列。

我想只是将新句子添加到新行中,并将所有尚未出现在列表中的非单词按列放置(此处,“和”将位于“您”的右侧)并再次对列表进行排序。但是,我还没有做到这一点,因为根据现有标签对新句子词频的排序已经不起作用(当再次出现“汽车”时,应将新句子的汽车词频写入新句所在行和“汽车”列,但当第一次出现例如“你”时,应将其出现频率写入新句所在行和新列中标为“你”)。

最佳答案

这并不完全是你所描述的,但是你的目标对我来说更有意义,按行而不是按列组织(无论如何,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.xby.y参数而不仅仅是 bymerge如果每个数据框中的名称不同,则可以指示合并的特定列。另外, suffix参数在 merge将控制如何为计数列赋予唯一名称。默认是附加 .x.y但你可以改变它。

关于R:按标签组合不同长度的频率列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8832554/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com