我想将 tiktoken python 模块与 R tidyverse mutate 函数一起使用。该模块本身可以正常工作,但在 tidyverse mutate 语句中使用时会抛出错误。错误是:
cnd_type()
中的错误:
! cnd
不是条件对象
这是一个可重现的示例:
library(reticulate)
tiktoken <- import("tiktoken")
encoding <- tiktoken$encoding_for_model("gpt-4")
#This works fine
prompt <- "John Lennon"
length(encoding$encode(prompt))
#Create df
beatles <- data.frame(name=c("John Lennon", "Paul McCartney",
"George Harrison", "Ringo Starr"),
instrument=c("Guitar", "Bass", "Guitar", "Drums"))
#run tiktoken on each cell of the name column
#this produces the error
beatles %>%
mutate(n_tokens = length(encoding$encode(name)))
提前致谢。
我通过使用 sapply 将函数应用于向量的每个元素来使其工作。
beatles %>%
mutate(n_tokens = sapply(name, function (x) {length(encoding$encode(x))}))