首页 > 解决方案 > 使用函数 get() 以编程方式分配 quanteda docvars

问题描述

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

一旦我定义了语料库,我通常会在整个代码中使用 function 调用它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 创建

原则上,我想一次将其推广到多个 docvar(例如,当它们存储在 data.frame 中时)。

有什么建议吗?

标签: rquanteda

解决方案


首先,我强烈建议您避免getassign尽可能地操纵这样的变量。这是一种非常间接的方法,正如您已经看到的那样,在尝试使用这些间接值来更新值时很容易中断。当你运行类似的东西时

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 

推荐阅读