[英]How to unlist objects in data.table that is made of data.table and lists made of data.table in R (example given)?
我正在尝试从 data.table 中取消列出值并将其设为 data.table,如下所述
given_y<-data.table(country=c("abc","xyz"),V2=(list(data.table(city=c("Del","Mum","Kol"),age=c(20,30,45)),data.table(city=c("Del","Mum"),age=c(30,45)))))
str(given_y)
Classes ‘data.table’ and 'data.frame': 2 obs. of 2 variables:
$ country: chr "abc" "xyz"
$ V2 :List of 2
..$ :Classes ‘data.table’ and 'data.frame': 3 obs. of 2 variables:
.. ..$ city: chr "Del" "Mum" "Kol"
.. ..$ age : num 20 30 45
.. ..- attr(*, ".internal.selfref")=<externalptr>
..$ :Classes ‘data.table’ and 'data.frame': 2 obs. of 2 variables:
.. ..$ city: chr "Del" "Mum"
.. ..$ age : num 30 45
.. ..- attr(*, ".internal.selfref")=<externalptr>
- attr(*, ".internal.selfref")=<externalptr>
expected_y<-data.table(customer=c("abc","abc","abc","xyz","xyz"),city=c("Del","Mum","Kol","Del","Mum"),age=c(20,30,45,30,45))
expected_y
customer city age
1: abc Del 20
2: abc Mum 30
3: abc Kol 45
4: xyz Del 30
5: xyz Mum 45
最终,我认为使用tidyr::unnest
是目前最好的选择:
as.data.table(tidyr::unnest(given_y, v2))
# country city age
# 1: abc Del 20
# 2: abc Mum 30
# 3: abc Kol 45
# 4: xyz Del 30
# 5: xyz Mum 45
我发现一些数据集需要添加keep_empty = TRUE
,但这不是必需的。 (例如,嵌入的帧之一有 0 行。)
这可能会失去一些内部效率,因为(我相信)它正在制作数据的副本( data.table
在可能的情况下真的很难避免......不确定这里是否可以避免)。
在 rdatatable 问题中有很多关于这个的讨论:
这是使用data.table
回答您的问题的解决方案
given_y[, unlist(.SD[[1]], recursive = F), by = country]
# country city age
# 1: abc Del 20
# 2: abc Mum 30
# 3: abc Kol 45
# 4: xyz Del 30
# 5: xyz Mum 45
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.