在R中对data.table的行进行偏度检验并生成outcome列
计算data.table每行数据的偏度并生成outcome列
需求:给现有data.table添加名为outcome的新列,用于表示每行数据的偏度:
- 若行数值为
(336, 0, 0, 0),高度左偏,outcome应为-1; - 若行数值为
(0, 0, 0, 336),高度右偏,outcome应为+1; - 其他情况
outcome介于-1和+1之间,比如(200, 100, 20, 16)对应的outcome约为-0.8,代表左偏。
数据结构及示例
temp_dt = structure(list(date = structure(c(19425L, 19426L, 19429L, 19430L, 19431L, 19432L, 19433L, 19436L, 19437L, 19438L, 19439L, 19440L ), class = c("IDate", "Date")), `-4` = c(336L, 0L, 310L, 315L, 321L, 284L, 230L, 117L, 43L, 35L, 36L, 31L), `-2` = c(0L, 0L, 21L, 21L, 18L, 47L, 86L, 171L, 105L, 192L, 224L, 208L), `2` = c(0L, 0L, 0L, 0L, 0L, 0L, 3L, 26L, 149L, 88L, 67L, 84L), `4` = c(0L, 336L, 5L, 2L, 0L, 6L, 20L, 21L, 39L, 20L, 10L, 9L)), row.names = c(NA, -12L), class = c("data.table", "data.frame"), sorted = "date")
输出结果:
> temp_dt date -4 -2 2 4 1: 2023-03-09 336 0 0 0 2: 2023-03-10 0 0 0 336 3: 2023-03-13 310 21 0 5 4: 2023-03-14 315 21 0 2 5: 2023-03-15 321 18 0 0 6: 2023-03-16 284 47 0 6 7: 2023-03-17 230 86 3 20 8: 2023-03-20 117 171 26 21 9: 2023-03-21 43 105 149 39 10: 2023-03-22 35 192 88 20 11: 2023-03-23 36 224 67 10 12: 2023-03-24 31 208 84 9
错误尝试:卡方检验
尝试用卡方检验计算,但结果无法区分偏度方向,左右偏的行outcome数值相同:
temp_dt[, outcome := chisq.test(.SD), by = .(date)]
输出结果:
> temp_dt date -4 -2 2 4 outcome 1: 2023-03-09 336 0 0 0 1008.00000 # 左偏和右偏行结果相同,不符合需求 2: 2023-03-10 0 0 0 336 1008.00000 # 左偏和右偏行结果相同,不符合需求 3: 2023-03-13 310 21 0 5 813.59524 4: 2023-03-14 315 21 0 2 841.52663 5: 2023-03-15 321 18 0 0 880.64602 6: 2023-03-16 284 47 0 6 646.98813 7: 2023-03-17 230 86 3 20 377.28319 8: 2023-03-20 117 171 26 21 190.93433 9: 2023-03-21 43 105 149 39 99.66667 10: 2023-03-22 35 192 88 20 217.03582 11: 2023-03-23 36 224 67 10 328.41246 12: 2023-03-24 31 208 84 9 286.81928
正确解决方案:基于moments包计算偏度
利用moments包的skewness函数,先将负方向的列值转为负数,再逐行计算偏度:
# 调整负方向列的数值符号 temp_dt[, `-4` := `-4` * -1] temp_dt[, `-2` := `-2` * -1] # 逐行计算偏度,生成outcome列 temp_dt[, outcome := apply(.SD, 1, moments::skewness), .SDcols = c("-4", "-2", "2", "4")]
最终输出结果:
> temp_dt date -4 -2 2 4 outcome 1: 2023-03-09 -336 0 0 0 -1.1547005 2: 2023-03-10 0 0 0 336 1.1547005 3: 2023-03-13 -310 -21 0 5 -1.1361798 4: 2023-03-14 -315 -21 0 2 -1.1393005 5: 2023-03-15 -321 -18 0 0 -1.1448131 6: 2023-03-16 -284 -47 0 6 -1.0565676 7: 2023-03-17 -230 -86 3 20 -0.6687309 8: 2023-03-20 -117 -171 26 21 -0.1431630 9: 2023-03-21 -43 -105 149 39 0.3021199 10: 2023-03-22 -35 -192 88 20 -0.5703578 11: 2023-03-23 -36 -224 67 10 -0.7789411 12: 2023-03-24 -31 -208 84 9 -0.6480315
内容的提问来源于stack exchange,提问作者Saurabh
相关产品推荐
相关产品推荐

