简体   繁体   中英

r data.table summarizing using more than one factor

i have below data.table

'data.frame':   66977 obs. of  16 variables:
 $ SUBS                         : int  
 $ CITY                         : Factor w/ 18 levels 
 $ VALUE_SEG                    : Factor w/ 7 levels 
 $ region                       : Factor w/ 5 levels 
 $ SUM.DATA_PPU_REV_DEC.        : num  
 $ SUM.DATA_BUNDLE_REV_DEC.     : int  
 $ SUM.DATA_USAGE_TOTAL_KB_DEC. : num  
 $ SUM.THIS_MONTH_REV_DEC.      : num  
 $ SUM.VOICE_ONNET_DURATION_DEC.: num  
 $ SUM.VOICE_ONNET_REV_DEC.     : num  
 $ SUM.VOICE_OFFNET_REV_DEC.    : num  
 $ SUM.SMS_ONNET_REV_DEC.       : num  
 $ SUM.SMS_OFFNET_REV_DEC.      : int  
 $ SUM.RECHARGE_DEC.            : int  
 $ STATUS_DEC                   : Factor w/ 5 levels 
 $ TYPE_DEC_2                   : Factor w/ 6 levels 

i want to group it by two of the Factor variables let's say VALUE_SEG & region, get the sum for number and create new coulm for each factor variable with count of observations. i tryied aggregate, ddply and others with varians type of errors :( thanks in advance

Here is an option using data.table

library(data.table)
setDT(data)[,lapply(.SD, function(x) if(is.numeric(x)) sum(x) else .N),
                          by= list(VALUE_SEG,region)]

I recommend you to separate numeric and factor variable and summarize using dplyr . It could be like

library(dplyr)

data %>% select(VALUE_SEG,region,SUM..... all numeric variables) %>% 
   group_by(VALUE_SEG,region) %>% summarize_each(funs(sum)) -> summary1

## For factors

data %>% select(VALUE_SEG,region,SUM..... all factors variables) %>% 
   group_by(VALUE_SEG,region) %>% summarize_each(funs(n)) -> summary2

## Then you can merge these results

Summary <- merge(summary1,summary2,by="VALUE_SEG")

For more details on using this package visit this link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM