使用函数 get() 以编程方式分配 quanteda docvars

Assign quanteda docvars programmatically with the function get()

我正在开发一个例程来自动定义 quanteda 中的几个语料库。我有几个控制脚本的参数,其中之一是将生成的语料库的名称。我可以使用函数 assign() 以编程方式轻松创建语料库,但我完全无法向其中添加任何 docvars

定义语料库后,我通常会在整个代码中使用函数 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 package (v1.0.0)

于 2021-02-17 创建

原则上,我想一次将其概括为多个文档变量(例如,当它们存储在 data.frame 中时)。

有什么建议吗?

首先,我强烈建议您 avoid get and assign when possible 像这样操作变量。这是一种非常间接的方法,正如您已经看到的那样,在尝试使用这些间接值来更新值时很容易中断。当你 运行 像

docvars( mycorpus, "year" ) <- thedocvars 

您正在 运行 一个名为 docvars<- 的特殊函数,该函数 returns 一个新对象,它将替换存储在 mycorpus 中的值。当你输入 get( nameofthecorpus ) 时,那不是一个可以替换的变量值,那是一个 returns 值的函数调用。所以如果你需要使用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