grouping and summing up dummy vars from caret R -


i have data this

dataset = data.frame(id = c(1,2,1,4,5,6), class = c('a', 'a', 'b', 'a', 'b', 'b') ) 

i want convert dummy vars caret's dummy vars doesn't collapse id returns same number of rows input. how group id 1 has both , b variables 1?

dummies <- caret::dummyvars(id ~ . , data=dataset) predict(dummies, newdata = dataset) 

in case use dcast function data.table:

library(data.table)  setdt(dataset)  dataset[,dummy:=1]     d2 = dcast(dataset,id~class,value.var = 'dummy',fun.aggregate = length) d2[is.na(d2)] = 0 

note solution return number of a's , b's found each id. if need 1 or 0 change example fun.aggregate

fun.aggregate = function(x) as.integer(length(x) >0) 

dummyvars works row wise , doesn't matter value in id


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -