我正在开发一个例程来自动定义几个语料库quanteda. 我有几个控制脚本的参数,其中一个是将要生成的语料库的名称。我可以很容易地用函数assign()
以编程方式创建语料库,但我完全无法向其中添加任何文档。
一旦定义了语料库,我通常在整个代码中用get()
函数调用它。我一直在广泛地使用这种方法,并取得了成功。由于某种原因,函数docvars()
似乎不接受用get()
调用的对象。
请看看下面我定义语料库的简单代码,然后尝试将一个docvar关联到它。
library(quanteda)
#> Package version: 2.1.2
#> Parallel computing: 2 of 16 threads used.
#> See https://quanteda.io for tutorials and examples.
#>
#> Attaching package: 'quanteda'
#> The following object is masked from 'package:utils':
#>
#> View
nameofthecorpus = "mycorpus"
mytext <- c( "This is a long speech made in 2020",
"This is another long speech made in 2021")
thedocvars <- c( "2020", "2021" )
assign( nameofthecorpus, corpus( mytext ) )
# I can have a summary of the corpus with get()
summary( get( nameofthecorpus ) )
#> Corpus consisting of 2 documents, showing 2 documents:
#>
#> Text Types Tokens Sentences
#> text1 8 8 1
#> text2 8 8 1
# Now I wand to add some docvars automatically
# This is where I get stuck
docvars( get( nameofthecorpus ), "year" ) <- thedocvars
#> Error in docvars(get(nameofthecorpus), "year") <- thedocvars: could not find function "get<-"
由reprex包(v1.0.0)创建于2021-02-17
原则上,我希望将其推广到一次多个文档(例如,当它们存储在data.frame中时)。
任何建议吗?
首先,我强烈建议在可能的情况下避免使用get
和assign
来操作这样的变量。这是一种非常间接的方法,正如您已经看到的,当尝试使用这些间接值来更新值时,很容易中断。当你运行像
docvars( mycorpus, "year" ) <- thedocvars
您正在运行一个名为docvars<-
的特殊函数,该函数返回一个新对象,该对象将替换存储在mycorpus
中的值。当您输入get( nameofthecorpus )
时,这不是一个可以替换的变量值,这是一个返回值的函数调用。因此,如果你需要使用get/assign
,你必须这样做
assign(nameofthecorpus, `docvars<-`(get( nameofthecorpus ), "year", thedocvars))
如果您从名称中检索值,则显式调用docvars
函数的转换版本以获取更新的对象值,然后将该值重新分配给原始变量名称。
一个更好的get/assign
方法通常是命名列表。就像
nameofthecorpus = "mycorpus"
mytext <- c( "This is a long speech made in 2020",
"This is another long speech made in 2021")
thedocvars <- c( "2020", "2021" )
mydata <- list()
mydata[[nameofthecorpus]] <- corpus( mytext )
summary( mydata[[nameofthecorpus]] )
docvars( mydata[[nameofthecorpus]], "year" ) <- thedocvars