Error in as.vector(x, mode) : cannot coerce type 'closure' to vector of type 'any'

28.2k views Asked by At

I'm doing some practice on broom package in R.

I ran the following

kclusts <- data.frame(k=1:9) %>% group_by(k) %>% do(fit=kmeans(data.frame, .$k))

I have received the following error

Error in as.vector(x, mode) : cannot coerce type 'closure' to vector of type 'any'

I was wondering whether I'm missing something in my string.

Hope you can help me out.

Juan

1

There are 1 answers

0
Josh Rumbut On

The question seemed to get solved in the comments, but I thought I would generalize it because I got a very similar error.

The reason you're getting that error can be found this way:

> typeof(data.frame)
[1] "closure"

You're effectively passing in the function that you use to create data frames, instead of a data frame.

The vignette for broom has a way to make code like this work:

library(dplyr)

set.seed(2014)
centers <- data.frame(cluster=factor(1:3), size=c(100, 150, 50), x1=c(5, 0, -3), x2=c(-1, 1, -2))
points <- centers %>% group_by(cluster) %>%
    do(data.frame(x1=rnorm(.$size[1], .$x1[1]),
                  x2=rnorm(.$size[1], .$x2[1])))

library(ggplot2)
ggplot(points, aes(x1, x2, color=cluster)) + geom_point()

points.matrix <- cbind(x1 = points$x1, x2 = points$x2)

# Notice points.matrix defined above
kclusts <- data.frame(k=1:9) %>% group_by(k) %>% do(kclust=kmeans(points.matrix, .$k))