提问人:Magnetar 提问时间:8/25/2021 最后编辑:Magnetar 更新时间:8/25/2021 访问量:666
不明白 Cannot Coerce type 'closure' 错误
Don't understand Cannot Coerce type 'closure' Error
问:
我看到这是一个常见问题,但我无法通过阅读其他帖子或尝试理解对我来说是新的函数式编程来理解该怎么做。函数是 R 中的闭包,封装了它们创建的环境?我的代码是:
# Remove numbers from text
minus_TextNum <- function(df, new.df){
new.df <- mutate(df, text = gsub(x = text, pattern = "[0-9]+|\\(.*\\)", replacement = "")) %>% # and/or whatever's in brackets
unnest_tokens(input = text, output = word) %>%
filter(!word %in% c(stop_words$word, "patient")) %>%
group_by(id) %>%
summarise(text = paste(word, collapse = " "))
return(new.df)
}
minus_TextNum(TidySymptoms)
错误如下:
错误:列 . 有问题我。X 不能胁迫 将“closure”类型为“character”类型的向量
mutate()
text
text = gsub(x = text, pattern = "[0-9]+|\\(.*\\)", replacement = "")
我不明白什么是类型闭包,这是一个简单的函数,适用于我创建用于测试的简单数据集。当我使用真实世界的数据集时出现问题。
任何反馈都值得赞赏。可重复的样品如下:
# Remove numbers and/or anything in brackets
# Test Data
mydata <- data.frame(id = 1:8,
text = c("112773 Nissan Micra, Car, (10 pcs)",
"112774 Nissan Micra, Car, (10 pcs)",
"112775 Nissan Micra, Car, (10 pcs)",
"112776 Volkswagon Beetle, Car, (3 pcs)",
"112777 Toyota Corolla, Car, (12 pcs)",
"112778 Nissan Micra, Car, (10 pcs)",
"112779 Toyota Prius, Car, (9 pcs)",
"112780 Toyota Corolla, Car, (12 pcs)"),
stringsAsFactors = F)
library(dplyr)
library(tidytext)
# remove numbers from text data
data(stop_words)
minus_TextNum <- function(df, new.df){
new.df <- mutate(df, text = gsub(x = text, pattern = "[0-9]+|\\(.*\\)", replacement = "")) %>% # and/or whatevers in brackets
unnest_tokens(input = text, output = word) %>%
filter(!word %in% c(stop_words$word, "car")) %>%
group_by(id) %>%
summarise(text = paste(word, collapse = " "))
return(new.df)
}
minus_TextNum(mydata)
dput(head(TidySymptoms, n = 10)) structure(list(word = c(“会厌”, “肿胀”, “阻碍”, “吞咽”, “图片”、“苯那君”、“泰诺”、“大约”、“30”、“分钟” )), row.names = c(NA, 10L), class = “data.frame”)
答:
1赞
Ronak Shah
8/25/2021
#1
TidySymptoms
数据中没有列。假设这是一个错误,并且您的数据中已经有该错误,您可以在函数中执行以下更改。id
- 无需传递给函数。
df.new
- 中的列称为 as,但您在函数中使用。
TidySymptoms
word
text
试试这段代码。
minus_TextNum <- function(df){
df.new <- mutate(df, text = gsub(x = word, pattern = "[0-9]+|\\(.*\\)", replacement = "")) %>%
unnest_tokens(input = text, output = word) %>%
filter(!word %in% c(stop_words$word, "patient")) %>%
group_by(id) %>%
summarise(text = paste(word, collapse = " "))
return(new.df)
}
minus_TextNum(TidySymptoms)
上一个:foldTree 分步评估
下一个:python 闭包何时进行捕获?
评论
minus_TextNum
需要两个参数,但你只传递了一个?如果您创建一个可重复的小示例以及预期的输出,则会更容易提供帮助。阅读有关如何给出可重复示例的信息。text
text()
gsub()
text
df
df$text = gsub(x=df$text, pattern....
new.df
function((
new.df <- minus_TextNum(df)
dplyr::mutate
df$
group_by
dplyr
df$
mutate()
gsub()