假设现在有这样一份 data.table:
Year_week artist_id number_of_events number_of_streams
1: 16/30 8296 1 957892 2: 16/33 8296 6 882282 3: 16/34 8296 5 926037 4: 16/35 8296 2 952704 5: 15/37 17879 1 89515 6: 16/22 22690 2 119653
添加季节性虚拟变量以转换为如下格式:
Year_week artist_id number_of_events number_of_streams Q2 Q3 Q4 1: 16/50 8296 1 957892 0 0 1
两种方法:
1)使用dcast , cut和sub :
dcast(DT[, Q := cut(as.integer(sub('.*/','',Year_week)), breaks = c(0,13,26,39,53), labels = paste0('Q',1:4))], Year_week + artist_id + number_of_events + number_of_streams ~ Q, value.var = 'Q', drop = c(TRUE,FALSE), fun = length)得到:
Year_week artist_id number_of_events number_of_streams Q1 Q2 Q3 Q41: 15/37 17879 1 89515 0 0 1 02: 16/22 22690 2 119653 0 1 0 03: 16/30 8296 1 957892 0 0 1 04: 16/33 8296 6 882282 0 0 1 05: 16/34 8296 5 926037 0 0 1 06: 16/35 8296 2 952704 0 0 1 0这是做什么的:
- as.integer(sub('.*/','',Year_week))从Year_week列中获取周数
- 使用cut您可以使用适当的标签将其划分为四分之一(另请参阅?cut )
- 使用dcast您可以将四分之一列转换为具有聚合函数( length )的宽格式。 通过在dcast函数中使用drop = c(TRUE,FALSE) ,可以确保包含所有季度。
笔记:
- Q列是一个有序因子,因此您也可以使用它来排列和过滤数据。
- 根据虚拟列的使用情况:您并不总是需要这些。 当您想将它们用作分组或过滤变量时,您可以使用Q变量。
- 但是,一些统计测试需要虚拟变量(证明dcast步骤是合理的)。
2)使用cut , sub和lapply :
DT[, Q := cut(as.integer(sub('.*/','',Year_week)), breaks = c(0,13,26,39,53), labels = paste0('Q',1:4)) ][, paste0('Q',1:4) := lapply(paste0('Q',1:4), function(q) as.integer(q == Q))][]这给出了类似的结果。 您只需检查其中一个季度标签是否在Q dcast ,而不是使用dcast进行转置。
使用数据:
DT <- fread(' Year_week artist_id number_of_events number_of_streams 16/30 8296 1 957892 16/33 8296 6 882282 16/34 8296 5 926037 16/35 8296 2 952704 15/37 17879 1 89515 16/22 22690 2 119653')

雷达卡


京公网安备 11010802022788号







