本文介绍了数据表到嵌套列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我想转换:library(data.table)n <- 12DT <- data.table( level1 = rep(paste0("Manu", 1:2), each = n / 2), level2 = rep(paste0("Dept", 1:4), each = n / 4), level3 = rep(paste0("Store", 1:n)))> DTlevel1 level2 level31: Manu1 Dept1 Store12: Manu1 Dept1 Store23: Manu1 Dept1 Store34: Manu1 Dept2 Store45: Manu1 Dept2 Store56: Manu1 Dept2 Store67: Manu2 Dept3 Store78: Manu2 Dept3 Store89: Manu2 Dept3 Store910: Manu2 Dept4 Store1011: Manu2 Dept4 Store1112: Manu2 Dept4 Store12 p>To this:goal <- list( Manu1 = list( Dept1 = paste0("Store", 1:(n / 4)), Dept2 = paste0("Store", (n/4 + 1):(n / 2)) ), Manu2 = list( Dept3 = paste0("Store", (n/2 + 1):(3 * n / 4)), Dept4 = paste0("Store", (3 * n / 4 + 1):n) ))> goal$Manu1$Manu1$Dept1[1] "Store1" "Store2" "Store3"$Manu1$Dept2[1] "Store4" "Store5" "Store6"$Manu2$Manu2$Dept3[1] "Store7" "Store8" "Store9"$Manu2$Dept4[1] "Store10" "Store11" "Store12" $ b b data.table 是什么方法?推荐答案 p>使用 assign 和朋友而不是全局< 可以使环境更严格,但这里一个快速和肮脏的做法:The environment can be made stricter using assign and friends instead of the global <<-, but here's a quick and dirty way of doing it:l = list()DT[, {l[[level1]][[level2]] <<- c(level3); NULL}, by = .(level1, level2)]l#$Manu1#$Manu1$Dept1#[1] "Store1" "Store2" "Store3"##$Manu1$Dept2#[1] "Store4" "Store5" "Store6"###$Manu2#$Manu2$Dept3#[1] "Store7" "Store8" "Store9"##$Manu2$Dept4#[1] "Store10" "Store11" "Store12" 这篇关于数据表到嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-19 20:29