繁体   English   中英

如何取消列出由 data.table 组成的 data.table 中的对象和由 R 中的 data.table 组成的列表(给出的示例)?

[英]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.

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