2016-04-14 15 views
0

müşteri kimliği ve ürün düzeyinde Ar verileri alınıyor: -Ben biçimine veri var

id  product mcg  txn 
101 gold  hotel 1 
101  gold  hotel 2 
101  clas  hotel 22 
101  clas  airline 23 

istediğim

  hotel_txn airline_txn 
101 gold 3    . 
101 clas 22    23 

kimse lütfen elde etmede yardımcı olabilir gibi çıktı bana Istenilen çıktı?

Temelde SAS deyiminde Case seçeneğine bir alternatif mi arıyorsunuz?

+0

deneyin 'kitaplığı (data.table); dcast (setDT (df1), id + ürün ~ mcg, value.var = "txn", toplam) ' – akrun

cevap

2

Biz Sen dplyr ve tidyr bunu yapmak için kullanabilirsiniz xtabs

xtabs(txn~idprod + mcg, transform(df1, idprod = paste(id, product), 
       mcg = paste0(mcg, "_txn"))) 
#   mcg 
#idprod  airline_txn hotel_txn 
# 101 clas   23  22 
# 101 gold   0   3 
0

kullanabilirsiniz:

library(dplyr) 
library(tidyr) 
df %>% group_by(id, product, mcg) %>% summarise(txn = sum(txn)) %>% spread(mcg, txn) 
Source: local data frame [2 x 4] 
Groups: id, product [2] 

    id product airline hotel 
    <int> <fctr> <int> <int> 
1 101 clas  23 22 
2 101 gold  NA  3 
+0

MCG sütununun bulunmadığı hata verir. –

1
Reshape2 en dcast fonksiyon Bu tür görevler için tasarlanmıştır

:

#creates your data frame 
df <- data.frame(id = c(101, 101, 101, 101), 
       product = c("gold", "gold", "clas", "clas"), 
       mcg = c("hotel", "hotel", "hotel", "airline"), 
       txn = c(1, 2, 22, 23)) 

#installs and loads the required package 
install.packages("reshape2") 
library(reshape2) 

#the function you would use to create the new data frame 
df2 <- dcast(df, id + product ~ mcg, value.var = "txn", sum) 

print(df2) 
    id product airline hotel 
1 101 clas  23 22 
2 101 gold  0  3 
+0

id ürün havayolu otel altın sınıfı 1 101 clas 23 22 3 45 CAn bu formdaki verileri alıyoruz? –

+0

@ankitagarwal talebinizi açıklayabilir misiniz? Yorumunuzda ne için sorduğunuzu anlamıyorum. – bshelt141