【发布时间】:2020-03-12 15:03:11
【问题描述】:
我正在处理列表receipts 的列表。 receipts 中的每个条目都包含一个代表收据的列表。收据的结构是一致的,看起来像这样。
> str(receipts[[1]])
List of 6
$ receipt_type : chr "SALESPERSON_ACTIVITY"
$ timestamp : POSIXct[1:1], format: "2020-01-01 09:29:00"
$ receipt_number: int 1195
$ POS : int 1
$ KNo : int 12
$ shift_number : int 9
receipt_number 也可能包含 NA 值。
我想将此列表转换为具有相应列(receipt_type、timestamp、receipt_number 等)的数据框。目前我正在使用这个
receipts_as_df <- as.data.frame(matrix(unlist(receipts), byrow=TRUE, ncol=length(receipts[[1]])))
这会将数据放入数据框中。可悲的是unlist 删除了有关数据类型的所有信息(我认为所有内容都被强制转换为character)。此外,列名也会丢失。因此,我有一个包含所有数据的数据框,但类型和列名丢失了。
我知道我可以手动重命名列和数据类型,但想知道是否有更舒适的方法来处理这种情况。
示例:目前数据框是这样的
> head(receipts_as_df)
V1 V2 V3 V4 V5 V6
1 SALESPERSON_ACTIVITY 1577867340 1195 1 12 9
2 CASH_REGISTER_MONITORING 1577867340 <NA> 1 12 9
3 PAYOUT_NOTIFICATION 1577867340 1196 1 12 9
4 TSE_ACTIVITY 1577869080 <NA> 1 12 9
5 BUSINESS_MODE_ACTIVITY 1577869080 <NA> 1 12 9
6 ZERO_RECEIPT 1577869140 1197 1 12 9
【问题讨论】:
-
do.call(rbind.data.frame, receipts)?还有dplyr::bind_rows(receipts)或data.table::rbindlist(receipts)。
标签: r list dataframe matrix coercion