2016-09-27 1 views
3

У меня есть следующий набор данныесводной таблицы в г с двоичным выходом

#datset 

id attributes value 
1 a,b,c  1 
2 c,d   0 
3 b,e   1 

Я хотел бы сделать сводную таблицу из них и присвоить двоичные значения для атрибута (от 1 до атрибутов, если они существуют, в противном случае назначить 0 к ним). Мой идеальный выход будет следующим:

#output 

id a b c d e Value 
1 1 1 1 0 0 1 
2 0 0 1 1 0 0 
3 0 1 0 0 1 1 

Любой отзыв действительно оценен.

ответ

1

Мы разделили столбец 'attributes' на ',', получим частоту с mtabulate от qdapTools и cbind с первой и третьей колонкой.

library(qdapTools) 
cbind(df1[1], mtabulate(strsplit(df1$attributes, ",")), df1[3]) 
# id a b c d e value 
#1 1 1 1 1 0 0  1 
#2 2 0 0 1 1 0  0 
#3 3 0 1 0 0 1  1 
1

С базой R:

attributes <- sort(unique(unlist(strsplit(as.character(df$attributes), split=',')))) 
cols <- as.data.frame(matrix(rep(0, nrow(df)*length(attributes)), ncol=length(attributes))) 
names(cols) <- attributes 
df <- cbind.data.frame(df, cols) 
df <- as.data.frame(t(apply(df, 1, function(x){attributes <- strsplit(x['attributes'], split=','); x[unlist(attributes)] <- 1;x})))[c('id', attributes, 'value')] 
df 
    id a b c d e value 
1 1 1 1 1 0 0  1 
2 2 0 0 1 1 0  0 
3 3 0 1 0 0 1  1 
Смежные вопросы