Reputation: 1
Im new to R and Stackoverflow.
I'm currently trying to apply onehot encoding to a vector. I tried to use dummyvars to accomplish it.
v <- sample(c("cat", "dog", "mouse"), 1000, replace = TRUE);
dmy <- dummyVars(" ~ .", data = v) <br />
dat_transformed <- data.frame(predict(dmy, newdata = v))
dat_transformed
I can make it work in data frames or data tables but not in a vector. How can I work around it?
Thanks.
Upvotes: 0
Views: 80
Reputation: 31
The default method of dummyVars
expects data
to be a data.frame
so you would need to wrap the vector in a data.frame
library(caret)
#> Loading required package: lattice
#> Loading required package: ggplot2
v <- data.frame(x = sample(c("cat", "dog", "mouse"), 10, replace = TRUE))
dmy <- dummyVars(~x, data = v)
dat_transformed <- predict(dmy, newdata = v)
dat_transformed
#> x.cat x.dog x.mouse
#> 1 1 0 0
#> 2 0 0 1
#> 3 0 0 1
#> 4 0 1 0
#> 5 1 0 0
#> 6 0 1 0
#> 7 1 0 0
#> 8 0 0 1
#> 9 1 0 0
#> 10 1 0 0
Upvotes: 1